Weird z-index behaviour preventing mouse interacti

2019-01-19 02:01发布

Every time I try to use z-index in a webpage to change the order of stacking overlapping divs, I seem to run into a problem where the div that is being forced lower becomes unresponsive to mouse events.

In my current situation I have:

<div class="leftcolumn">
<div class="leftbar"></div> <!-- a 95px wide bar on the left -->
...
<h3>header</h3> <!-- a little header sitting inside the leftbar
...
</div>

By default the h3 isn't showing - it's hidden behind the leftbar. If I add z-index: 5; to the h3, it still doesn't show.

So I add z-index: -1 to the leftbar. Now it's hidden behind the leftcolumn - but at least h3 shows.

So I add z-index: -2 to the leftcolumn. Now everything looks right - but you can't click on anything inside leftcolumn. The mouse cursor doesn't change from an arrow.

I get this exact behaviour in both Chrome and Firefox. IE7 doesn't show the leftbar at all, but at least stuff is clickable.

So, am I misunderstanding z-index, or is there a bug in both FF and Chrome here? Can z-index be effectively used for this kind of stuff, or do I have to find another way?

(I can change the HTML, but the less, the better.)

3条回答
Root(大扎)
2楼-- · 2019-01-19 02:48

Even though the leftcolumn content is visible, the leftbar div is now sitting on top of it, likely with a transparent background. Ideally you would want to modify the HTML so that the H3 resides within the leftbar, but if that is not an option, you may need to apply z-index to specific elements within the leftcolumn in order to pull them above elements in the leftbar.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-19 02:49

Ok, 10 seconds later I discover that using only positive z-index'es makes the problem go away. Perhaps negative z-index means the object is below the level that the mouse cursor notionally lives?

查看更多
家丑人穷心不美
4楼-- · 2019-01-19 02:51

Do you know that in order for z-index to work right, you need to position your elements, even if they're simply position: relative (which doesn't change their position any but allows you to use z-index). That way, you should be able to give leftbar a position of, say, 2 and your h3 a position of, say, 3. And your h3 should be on top.

You can use any position type as long as you have one.

For recap:

#leftcolumn { position: absolute; z-index: 1; }

#leftbar { position: relative; z-index: 2; }

h3 { position: relative; z-index: 3; }

查看更多
登录 后发表回答