您可以在不添加样式属性的情况下使用JavaScript对元素进行样式设置吗?

问题描述 投票:0回答:3

当您使用JavaScript编写element.style = "..."时,会将style属性添加到添加样式的元素。有没有style属性,没有任何库的添加样式的方法吗?

javascript css
3个回答
1
投票

如果可以提出一个以该元素为目标的选择器,另一个选择是附加一个包含该选择器的样式表:

const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = 'div { color: blue; }';
<div>Some div</div>

如果允许您以某种方式更改元素,例如添加类或其他属性,那会更可靠:

const div = document.querySelector('div');
const className = `_${('' + Math.random()).slice(2)}`;
div.classList.add(className);
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = `.${className} { color: blue; }`;
<div>Some div</div>

0
投票

使用JS,您可以将任何内容写入DOM,包括<style>标签。因此,例如:

const el = document.getElementById('changeColor');
el.onclick = function(e) { 
   const s = document.createElement('style');
   s.innerHTML = '.box { background-color: yellow; }';
   document.querySelector('body').appendChild(s);
}
.box {
   width: 150px;
   height: 150px;
   background-color: red;
   color: white;
   padding: 20px;
}

#changeColor {
   margin: 10px 0;
}
<body>
   <button type="button" id="changeColor">Change It</button>
   <div class="box">This is a box</div>
</body>

0
投票
  • styles标签内添加CSS类
  • 在加载文档时,使用DOMContentLoaded事件将一个类添加到元素中>]
  • 通过标签名称获取要素
  • 使用vanillaJS中的setAttribute方法将CSS类添加到标签元素中>]
  • 通过这种方式,它可能是更易于维护的yoru代码,因为您在css级别进行了更改,而JS会自动将声明的css类中的值tanken放入JS]
  •     <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width">
          <title>Example</title>
          <style>
            .styles {
              color: red;
            }
          </style>
        </head>
        <body>
        <p>Hello there</p>
        <script>
          let paragraph = document.querySelector("p")
          
          document.addEventListener("DOMContentLoaded", () => {
            paragraph.setAttribute("class", "styles")
          })
        </script>
        </body>
        </html>
© www.soinside.com 2019 - 2024. All rights reserved.