且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用JavaScript将所有计算出的CSS样式移动到一个元素并将其应用于另一元素?

更新时间:2023-09-14 15:22:52

这是我想出的解决方案,它混合了document.defaultView.getComputedStyle和jQuery的.css():

This is a solution I figured out, it mixes document.defaultView.getComputedStyle and jQuery's .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和内联样式),并使用jQuery的.css()将其设置为另一个div

What this does is copy the computed style object, including the style.css and the inline style, and set it to the other div using jQuery's .css()

我希望我不会误解这个问题,而这正是您所需要的.

I hope I didn't misunderstand the question and that this is what you need.

我忘记的是您要求移动"样式而不是复制样式.使用jQuery的.removeClass()和.attr()删除样式属性,从上一个div中删除样式非常简单,但是要记住,如果有任何样式规则应用于元素的ID,无法阻止它们被应用.

Something I forgot is that you asked to 'move' the style rather than copy it. It's very simple to remove styles from the previous div using jQuery's .removeClass() and using .attr() to remove the style attribute, but you have to keep in mind that if there are any style rules being applied to the element's ID, there's no way to keep them from being applied.