CSS属性更改OnClick

时间:2012-04-25 12:58:20

标签: javascript jquery html css

我有一个简单的绝对定位,通过CSS包括z-index HTML:

<div id="one"> test </div>
<div id="two"> test </div>
<div id="three"> test </div>

CSS:

#one{
height: 200px;
width: 150px;
background: #a8d14f;
position: absolute;
left: 10px;
top: 30px;
z-index: 10;
}
#two{
height: 200px;
width: 150px;
background: #f97273;
position: absolute;
left: 150px;
top: 30px;
z-index: 15;
}
#three{
height: 200px;
width: 150px;
background: #43b8b0;
position: absolute;
left: 300px;
top: 30px;
z-index: 12;
}

需要: OnClick更改选定的一些CSS属性,如position,z-index,background

6 个答案:

答案 0 :(得分:6)

以下是one元素的onclick事件示例,该事件将更改其z-index

$(function(){
  $("#one").click(function(){
     $(this).css("z-index", 2);
  });
});

由此你应该能够找出如何做其余的事情。如果没有,那么再研究一下jQuery的用法。我们不是来为你做这项工作。

答案 1 :(得分:2)

或者没有jQuery:

document.getElementById("one").onclick = function() {
    with (this.style) {
        color = "red";
        position = "relative";
        zIndex = "10";
    }
};​

答案 2 :(得分:1)

尝试这样的事情。 Here's more details on how to change css properties with jQuery

$("#one").click(function(){
    $(this).css("position", "absolute");
});

答案 3 :(得分:1)

或者不使用jQuery

var one = document.getElementById("one");
one.addEventListener("click", function() {
    one.style.zIndex = 5;
}, false);

答案 4 :(得分:0)

这是一个有效的jsFiddle:http://jsfiddle.net/qJURY/ 这是使用的代码:

$("div").click(function(){
    var z = parseInt($(this).css("z-index"));
    z += 10;
    $(this).css("z-index", z);
})
​

答案 5 :(得分:0)

试试这个:

$('#one').click(function(){
   $(this).css("background-color","yellow");
   $(this).css("z-index", 1);

});

替代你可以使用普通的javascript:

document.getElementById('one').style.zIndex = '1'