开发者

jQuery show and z-index

开发者 https://www.devze.com 2023-01-27 04:46 出处:网络
The following code is not working as expecting : EDIT: Sorry for the misunderstanding, I simplified too much my issue, here is the real issue I\'开发者_运维百科m facing: http://jsfiddle.net/bc6hr/

The following code is not working as expecting :

EDIT:

Sorry for the misunderstanding, I simplified too much my issue, here is the real issue I'开发者_运维百科m facing: http://jsfiddle.net/bc6hr/

HTML:

<div id="1">div 1</div>
<div id="2">div 2</div>

CSS:

div {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    background: white;
}
#1 {
    z-index: 2;
}

JS (jQuery):

$("div").hide();
$("#1").show();
$("#2").show();

I must be missing something, because from what I know, this code should be displaying "div 1" fading to "div 2", but it is actually rendering "div 2" from the start.

How could I make it displaying "div 1" knowing that I must hide all divs before? I thought using z-index was a good try, but maybe I'm wrong...


First of all your id attribute is invalid. You cannot start an id with number.

Updated your jsfiddle.


Change your IDs to valid ones ... (no starting with numbers)

example http://jsfiddle.net/mBWcM/3/


I believe the id cannot start with a number. When the div's ids are changed to d1 and d2, they work:

http://jsfiddle.net/mBWcM/4/


The problem is, that 1 and 2 are not valid IDs. Therefore either jQuery or the CSS parser doesn't recognize the element. Use a and b instead and see it working: http://jsfiddle.net/mBWcM/1/

The problem is, that when you call the z-index change in JavaScript, the divs are not even there (the code lives in the head element and is immediately executed). See the fiddler page's source.

Work around: Embrace everything in the "Start, when DOM is ready" construct:

jQuery(document).ready(function () {
   // your code here
});

Edit: Actually, I think it's a jsFiddle issue. When I re-load the page once or twice, it happens, that "div1" remains visible, the other times, it's "div2". I just saw, that jsFiddle indead wraps the code in a window.onload equivalent.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号