简体   繁体   English

如何使用 JavaScript no jQuery 使用带有数据属性的内联样式

[英]How can I use inline style with data attribute using JavaScript no jQuery

I can use in my html file like this我可以像这样在我的 html 文件中使用

<div data-width="250px"></div>
<div data-width="calc(100% - 300px);"></div>

I need to output like this我需要这样输出

<div data-width="250px" style="width:250px"></div>
<div data-width="calc(100% - 300px);" style="width:calc(100% - 300px);"></div>

you may use like following你可以使用如下

<script>
    document.getElementsByTagName("div")[0].setAttribute("data-width","250px");
    document.getElementsByTagName("div")[0].setAttribute("style","width:250px");
    document.getElementsByTagName("div")[1].setAttribute("data-width","calc(100% - 300px)");
    document.getElementsByTagName("div")[1].setAttribute("style","width:calc(100% - 300px);");
</script>

You can simply use querySelectorAll along with forEach loop to apply the style width property to your divs which are stored in the data-width attribute.您可以简单地使用querySelectorAllforEach循环将style宽度属性应用于存储在data-width属性中的divs

To get the data-width from each element we can use getAttribute method.要从每个元素获取data-width ,我们可以使用getAttribute方法。

Edit: You can select multiple elements like section , h1 , span in the same querySelectorAll编辑:您可以在同一个querySelectorAll选择多个元素,如sectionh1span

Live Demo: Using only JavaScript现场演示:仅使用 JavaScript

 let getDivs = document.querySelectorAll('div, h1, section') getDivs.forEach(function(div) { let data = div.getAttribute('data-width') div.style.width = data })
 <div data-width="250px">1</div> <div data-width="calc(100% - 300px)">2</div> <h1 data-width="210px">3</h1> <section data-width="150px">4</section>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用jquery将内联样式与数据属性和浏览器前缀一起使用 - How can I use inline style with data attribute and browser prefix using jquery 使用 JavaScript no jQuery 的数据属性的内联样式,改变颜色 - Inline style with data attribute using JavaScript no jQuery, changing color 如何使用带有css3前缀的jquery数据属性添加内联css - How can I add inline css using jquery data attribute with css3 prefix 如何从内联样式属性中获取值并将其放入最接近的输入值中? jQuery的 - How can I get a value from an inline style attribute and put inside the closest input value? jQuery 我怎样才能添加一个 <use> 使用jQuery(如果需要,还是纯JavaScript)内联SVG? - How can I add a <use> to an inline SVG using jQuery (or plain JavaScript if needed)? 如何使用引导程序,javascript,jquery制作嵌入式日历 - how can I make a Inline calendar using bootstrap, javascript, jquery 如何使用jquery或javascript摆脱内联样式 - How to get rid the inline style using jquery or javascript 如何在带有 v-bind:style 的内联 css 中使用 v-for 列表中的数据? - How can I use data from v-for list in inline css with v-bind:style? 如何找到设置元素内联样式的JavaScript? - How can I find the JavaScript that is setting the inline style of an element? 如何使用数据属性和jQuery使链接可以点击? - How can I use a data attribute and jQuery to make a link clickable or not?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM