我有一个外部样式表,将一些样式应用于给定的元素.我想能够将这些样式(使用
JavaScript)移动到不同的元素,而不需要先前了解应用的样式.
CSS:
td { padding: 5px }
div { }
HTML:
<td>
<div>
Apply the TD styles to this DIV (instead of the TD).
</div>
</td>
JavaScript:
$(document).ready(function(){
$('tr').children('td').each(function(){
//move the td styles to div
});
});
我该如何实现?
更新:要清楚,我无法控制CSS.我无法知道应用什么样式.我想要解决的问题是能够使用元素并复制其样式(可能是未知的)并将其应用于不同的元素.
解决方法
这是我想出的一个解决方案,它混合了document.defaultview.getComputedStyle和jQuery的.css():
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" > </script>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="test" style="background-color: #FF7300">
<p>Hi</p>
</div>
<a href="#" id="button">Apply styles</a>
<script>
$("#button").click(function() {
var element = document.getElementById("test");
$("#victim").css(document.defaultview.getComputedStyle(element,null));
});
</script>
<div id="victim">
<p>Hi again</p>
</div>
</body>
//style.css
#test {
border: 3px solid #000000;
}
这样做是复制计算的样式对象,包括style.css和inline样式,并使用jQuery的.css()将其设置为其他div,
我希望我没有误解这个问题,这就是你所需要的.
编辑:我忘记的是你要求“移动”风格,而不是复制它.使用jQuery的.removeClass()和使用.attr()来删除style属性,从前一个div中删除样式非常简单,但是您必须记住,如果要对元素的ID应用任何样式规则,那么没有办法阻止他们被应用.