如何在JavaScript中使用z索引

时间:2010-08-02 14:01:20

标签: javascript jquery

zindex的语法是什么?

我试过这个

document.getElementById('iframe_div1').style.zIndex =2000;
document.getElementById('iframe_div1').style.z-index =2000;

它不起作用,甚至没有显示错误。

这是我的片段。它在HTML中运行良好,但我想在jQuery或JavaScript中设置此CSS属性。顶部/位置属性不起作用......

  

的z-index:1200像素;顶:450像素;位置:绝对的;右:300像素;

document.getElementById('iframe_div1').style.display='block';
$("#iframe_div1").css("z-index", "500");
$("#iframe_div1").css("right", "300");
$("#iframe_div1").css("top", "450");
document.getElementById('iframe_div1').style.position = "absolute";

这段代码并不像我预期的那样完美。我想移动页面的div中心,但它只是将我的div移动到页面的底部。

5 个答案:

答案 0 :(得分:12)

document.getElementById('iframe_div1').style.zIndex = "2000";没问题。只需确保positionabsoluterelative。像这样,

document.getElementById('iframe_div1').style.position = "relative"; // could also be absolute

答案 1 :(得分:8)

前者应该可以正常工作。使用像Firebug的“检查元素”这样的DOM检查器来确定是否可以分配值,但是没有达到预期的效果。

在jQuery中,它将是

 $("#iframe_div1").css("z-index", "2000");

答案 2 :(得分:2)

正如此链接所提到的,zIndex仅在元素定位时才有效,您使用的是position: absolute;吗?

http://www.w3schools.com/jsref/prop_style_zindex.asp

答案 3 :(得分:0)

$('#iframe_div1').css({
        right : '300px',
        top : '450px',
        border : '1px solid red',
        color : '#f00'
});

谢谢问题已修复

答案 4 :(得分:0)

  

...但它只是移动我的div底部...

becouse:

document.getElementById('iframe_div1').style.display='block';

必须:

document.getElementById('iframe_div1').style.display='relation';

//or

document.getElementById('iframe_div1').style.display='absolute';