我想将一些 CSS 样式从一个 DIV 复制到另一个 DIV。
点击“ONE”DIV
然后 jQuery 从 ARRAY 读取 CSS 属性列表
然后将这些属性从 DIV“ONE”复制到 DIV“TWO”。
这是我的尝试,但没有成功。这是怎么回事?
HTML
<div class="one">Click HERE on this DIV, to TRANSFER CSS properties From this ONE</div>
<div class="two">To this TWO</div>
CSS
* {
background-color:gray;
}
.one {
color: red;
font-size:12px;
width: 100px;
height: 100px;
background-color: white;
margin: 20px;
padding: 20px;
font-weight: bold;
}
.two {
font-size:20px;
color: blue;
width: 200px;
height: 200px;
background-color: yellow;
margin: 20px;
padding: 20px;
}
jQuery
$(document).ready(function(){
$("div.one").click(function(){
var $array = ['color','width','height', 'background-color', 'font-weight', 'font-size'];
$(this).each( $array , function(item, value){
$("div.two").css(value, $(this).css(value));
});
});
});
最佳答案
- 选择
jQuery
在 JSFiddle 的左侧面板中。
- 使用
$.each(array, fn)
而不是$().each(array, fn)
. - 将
$(this)
存储在变量中,例如$this = $(this)
。在循环内,this
引用数组元素,而不引用被单击的 DOM 元素。 - (非关键)不要在非 jQuery 对象前面加上
$
前缀。
演示:http://jsfiddle.net/meU9M/2/
$(document).ready(function(){
$("div.one").click(function(){
var array = ['color','width','height', 'background-color', 'font-weight', 'font-size'];
var $this = $(this);
$.each( array , function(item, value) {
$("div.two").css(value, $this.css(value));
});
});
});
关于jquery - 通过 jQuery 在 DIV 之间复制选定的 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10160954/