Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - The z-index property is not behaving as expected

I am currently working on a site in which I need hearts. I create the hearts using JavaScript and CSS:

function heart(x, y, pos, width, r) {
    var height = width + (width / 2 + 1);
    var heart = "position:" + pos + ";left:" + x + "px;top:" + y + "px;width:" + width + "px;height:" + height + "px;transform: rotate(" + r + "deg);-moz-transform: rotate(" + r + "deg);-webkit-transform: rotate(" + r + "deg);";
    var slices = "left:" + width + "px;width:" + width + "px;height:" + height + "px";
    $("body").append('<div class="heart" style="' + heart + '"><div class="slice" style="' + slices + '"></div><div class="slice2" style="' + slices + '"></div></div>');
}

I'm currently trying to put a large heart under a box using:

heart(282, 69, "absolute", 230, 0);

However, z-index is not doing anything, as you can see in my JSFiddle example.

I've even tried setting the z-index of the universal selector (*) to 0 while changing the z-index of the box to 10 !important; but that didn't work either. I am puzzled about why this is happening, but I'm pretty sure it has to do with the dynamic heart. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An element needs to be positioned in order for the z-index to work. See the visual formatting modal.

In this instance, you could simply add position:relative to the box.

UPDATED EXAMPLE HERE

.welcome {
    z-index:10;
    position: relative;
    background: #fff;
    margin: 0 auto;
    width: 200px;
    padding: 100px;
    text-align: center;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 3px;
    -moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 3px;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 3px;
}

No need for !important either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...