jQuery 显示和 z-index
以下代码未按预期工作:
编辑:
抱歉造成误解,我过于简化了我的问题,这是我面临的真正问题:http://jsfiddle。网/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();
我一定错过了一些东西,因为据我所知,这段代码应该显示“div 1”淡入“div 2”,但它实际上从一开始就渲染“div 2”。
知道我之前必须隐藏所有 div,如何让它显示“div 1”?我认为使用 z-index
是一个很好的尝试,但也许我错了......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,您的
id
属性无效。 id 不能以数字开头。更新了您的jsfiddle。
First of all your
id
attribute is invalid. You cannot start an id with number.Updated your jsfiddle.
将您的 ID 更改为有效的 ID ...(不能以数字开头)
示例 http://jsfiddle.net/mBWcM/3/
Change your IDs to valid ones ... (no starting with numbers)
example http://jsfiddle.net/mBWcM/3/
我相信 id 不能以数字开头。当 div 的 id 更改为 d1 和 d2 时,它们将起作用:
http://jsfiddle.net/mBWcM/4/
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/
问题是,1
和2
不是有效的 ID。因此 jQuery 或 CSS 解析器都无法识别该元素。使用a
和b
来代替并查看它的工作原理:http: //jsfiddle.net/mBWcM/1/问题是,当您在 JavaScript 中调用 z-index 更改时,div 甚至不存在(代码位于
head 中
元素并立即执行)。请参阅 fiddler 页面的源代码。解决方法:拥抱“当 DOM 准备就绪时开始”构造中的所有内容:
编辑: 实际上,我认为这是一个 jsFiddle 问题。当我重新加载页面一两次时,“div1”仍然可见,其他时候,它是“div2”。我刚刚看到,jsFiddle 确实将代码包装在
window.onload
等效项中。The problem is, that1
and2
are not valid IDs. Therefore either jQuery or the CSS parser doesn't recognize the element. Usea
andb
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:
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.