Joi*_*oie -1 html javascript css jquery this
我$(this)用来获取HTML元素的css属性,但它只适用于其中一个.这些项目是相同的,除了正在工作的所有项目都相对定位.
这是我的HTML:
<div class="red" id="color"></div>
<div class="orange" id="color"></div>
<div class="yellow" id="color"></div>
<div class="green" id="color"></div>
<div class="blue" id="color"></div>
<div class="purple" id="color"></div>
<div class="pink" id="color"></div>
<div class="black" id="color"></div>
<div class="white" id="color"></div>
<br/><br/><br/><br/><br/>
<div class="space"></div>
Run Code Online (Sandbox Code Playgroud)
这是我的jQuery:
$(document).ready(function(){
$('#color').click(function(){
var color = $(this).css('background');
$('.space').css('background',''+color+'');
});
});
Run Code Online (Sandbox Code Playgroud)
这是我的CSS:
body {
margin-top:55px;
margin-left:60px;
margin-right:60px;
margin-bottom:60px;
}
#color {
float:left;
border:1px solid #A3A3A3;
cursor:pointer;
}
.red {
height:49px;
width:49px;
background:#8A0B0B;
}
.orange {
height:49px;
width:49px;
background:#E89229;
position:relative;
left:17px;
}
.yellow {
height:49px;
width:49px;
background:#EBD508;
position:relative;
left:34px;
}
.green {
height:49px;
width:49px;
background:#3B8242;
position:relative;
left:51px;
}
.blue {
height:49px;
width:49px;
background:#6E97D5;
position:relative;
left:68px;
}
.purple {
height:49px;
width:49px;
background:#542462;
position:relative;
left:85px;
}
.pink {
height:49px;
width:49px;
background:#FACCFA;
position:relative;
left:102px;
}
.black {
height:49px;
width:49px;
background:#000000;
position:relative;
left:119px;
}
.white {
height:49px;
width:49px;
background:#ffffff;
position:relative;
left:136px;
}
.space {
height:657px;
width:500px;
border:2px solid #A3A3A3;
}
Run Code Online (Sandbox Code Playgroud)
您对如何使jQuery适用于所有div有什么想法吗?提前致谢.
这是因为你有多个相同的id color
<div class="red" id="color"></div>
<div class="orange" id="color"></div>
<div class="yellow" id="color"></div>
Run Code Online (Sandbox Code Playgroud)
您可以更改为以下内容并指定类,以将事件处理程序附加到具有类的所有元素 .color
<div class="color red"></div>
<div class="color orange"></div>
<div class="color yellow"></div>
Run Code Online (Sandbox Code Playgroud)
$('.color').click(function() { // class selector
var color = $(this).css('background');
$('.space').css('background',''+color+'');
});
Run Code Online (Sandbox Code Playgroud)
同样如您对元素样式的评论中所述.由于我们正在交换类的id,因此请记住相应地应用您的样式规则
#color { ... }
Run Code Online (Sandbox Code Playgroud)
=>
.color { ... }
Run Code Online (Sandbox Code Playgroud)