最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Problem with z-index - Stack Overflow

programmeradmin2浏览0评论

I must be missing something about z-index. Look at this code:

var span = document.createElement('span');
span.innerHTML = '<div style="background: none repeat scroll 0px 0px' +
    '#000000; opacity: 0.7; display: block; top: 0px; bottom: 0px; ' +
    'left: 0px; right: 0px; position: fixed; z-index: 1;"></div>';

span.innerHTML += '<div id="fancybox-wrap" style="opacity: 1; ' +
    'width: 420px; height: 200px; top: 467px; left: 481.5px; ' +
    'display: block; z-index: 2; ' +
    'border: 1px solid black;">Inside div</div>';
document.body.appendChild(span);

Based on the fact that the second div has a higher z-index, should it be on top of the first div?

Take a look at / to see what I mean

I must be missing something about z-index. Look at this code:

var span = document.createElement('span');
span.innerHTML = '<div style="background: none repeat scroll 0px 0px' +
    '#000000; opacity: 0.7; display: block; top: 0px; bottom: 0px; ' +
    'left: 0px; right: 0px; position: fixed; z-index: 1;"></div>';

span.innerHTML += '<div id="fancybox-wrap" style="opacity: 1; ' +
    'width: 420px; height: 200px; top: 467px; left: 481.5px; ' +
    'display: block; z-index: 2; ' +
    'border: 1px solid black;">Inside div</div>';
document.body.appendChild(span);

Based on the fact that the second div has a higher z-index, should it be on top of the first div?

Take a look at http://jsfiddle/qwertymk/TQSkX/ to see what I mean

Share Improve this question asked Dec 23, 2010 at 18:43 qwertymkqwertymk 35.4k30 gold badges124 silver badges184 bronze badges 2
  • You can't put a div inside a span. – Quentin Commented Dec 23, 2010 at 18:45
  • Changing it to a div, didn't change anything. jsfiddle/qwertymk/TQSkX/2 – qwertymk Commented Dec 23, 2010 at 18:47
Add a ment  | 

2 Answers 2

Reset to default 7

z-index does not apply to elements that are position: static (which is the default)

You need to set the position on the second div in the css for it to read the z-index.

add position: relative; to your second div and it should work fine.

   var span = document.createElement('span');
    span.innerHTML = '<div style="background: none repeat scroll 0px 0px' +
        '#000000; opacity: 0.7; display: block; top: 0px; bottom: 0px; ' +
        'left: 0px; right: 0px; position: fixed; z-index: 1;"></div>';

    span.innerHTML += '<div id="fancybox-wrap" style="opacity: 1; ' + 
        'width: 420px; height: 200px; top: 467px; left: 481.5px; ' +
        'display: block; position: relative; z-index: 2; ' +
        'border: 1px solid black;">Inside div</div>';
    document.body.appendChild(span);
发布评论

评论列表(0)

  1. 暂无评论