【问题标题】:how to copy style attribute from element A to B using javascript?如何使用javascript将样式属性从元素A复制到B?
【发布时间】:2019-09-03 09:11:27
【问题描述】:

我想将 css 内联样式从一个元素分配给另一个元素。 例子。

我想复制样式表 btn1 并分配给 btn 2

<button id="btn1" style="font-size: 10px;background-color: #4CAF50;  padding: 10px 24px;">Button 1</button>

  <button id="btn2" style="font-size: 10px;background-color: rgb(93, 16, 3); background:beige ; padding: 10px 24px;">Button 2</button>

【问题讨论】:

标签: javascript


【解决方案1】:

从第一个元素获取样式属性并使用该值设置另一个元素的样式属性。

let styles = document.querySelector('#btn1').getAttribute('style')

document.querySelector('#btn2').setAttribute('style', styles)
<button id="btn1" style="font-size: 10px;background-color: #4CAF50;  padding: 10px 24px;">Button 1</button>
<button id="btn2">Button 2</button>

【讨论】:

    【解决方案2】:

    您可以使用 HTML 元素的 getAttributesetAttribute 方法,例如:

    const btn1 = document.getElementById("btn1");
    const btn2 = document.getElementById("btn2");
    
    btn2.addEventListener("click", copyStyles);
    
    function copyStyles(){
      const style = btn1.getAttribute("style");
      btn2.setAttribute("style", style);
    }
    <button
      id="btn1"
      style="font-size: 10px; background-color: #4CAF50;  padding: 10px 24px;"
    >Button 1</button>
    
    <button
      id="btn2"
      style="font-size: 10px; background-color: rgb(93, 16, 3); background:beige; padding: 10px 24px;"
    >Button 2</button>

    【讨论】:

      【解决方案3】:

      使用getAttribute()从一个元素获取样式属性,并使用setAttribute()应用到其他元素

      document.querySelector('#btn2').setAttribute('style',document.querySelector('#btn1').getAttribute('style'))
      <button id="btn1" style="font-size: 10px;background-color: #4CAF50;  padding: 10px 24px;">Button 1</button>
      
        <button id="btn2" style="font-size: 10px;background-color: rgb(93, 16, 3); background:beige ; padding: 10px 24px;">Button 2</button>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-14
        • 1970-01-01
        • 2011-04-22
        • 2010-12-23
        • 2022-06-14
        • 2013-10-18
        • 1970-01-01
        相关资源
        最近更新 更多