简体   繁体   English

jQuery CSS 到纯 Javascript

[英]jQuery CSS to pure Javascript

I am trying to use jQuery as little as possible and I would like to translate some jQuery code to pure JS.我正在尝试尽可能少地使用 jQuery,并且我想将一些 jQuery 代码转换为纯 JS。

I have this:我有这个:

$(".myDiv").css({"width": 500});

What is the pure JS equivalent of the code above?上面代码的纯 JS 等价物是什么?

var els = document.querySelectorAll('.myDiv');

// If you want to get elements using its class name
// var els = document.getElementsByClassName('myDiv');

for(var i = 0, length = els.length; i < length; i++) {
   els[i].style.width = '500px';
}

By using forEach :通过使用forEach

var els = document.querySelectorAll('.myDiv');

els.forEach(function(el, ind) {
  el.style.width = '500px';
});

JS Fiddle JS小提琴

There are a few ways to achieve the same affect, but you could go with something like this:有几种方法可以实现相同的效果,但您可以使用以下方法:

document.querySelectorAll('.myDiv').forEach(function(el) {
  el.style.width = '500px';
});

querySelectorAll selects all of a particular CSS selector as a collection of DOM elements. querySelectorAll 选择所有特定 CSS 选择器作为 DOM 元素的集合。 forEach iterates through the collection, passing the currently selected element to the inner function, which is then styled with style.width. forEach 遍历集合,将当前选定的元素传递给内部函数,然后使用 style.width 对其进行样式设置。

document.querySelectorAll('.myDiv').forEach(function(elem) {
    elem.style.width = "500px";
})

querySelectorAll gets the elements, then you iterate over the elements and set the style for each one. querySelectorAll获取元素,然后遍历元素并为每个元素设置样式。

You just need to use document.getElementsByClassName() to get all the elements with this class and then iterate over them and use style.width to change their width:您只需要使用document.getElementsByClassName()来获取具有此类的所有元素,然后遍历它们并使用style.width更改它们的宽度:

Array.from(document.getElementsByClassName("myDiv")).forEach(function(div) {
  div.style.width = "500px";
});

Demo:演示:

 Array.from(document.getElementsByClassName("myDiv")).forEach(function(div) { div.style.width = "100px"; });
 .myDiv{ background-color:yellow; }
 <div class="myDiv">A</div>

Note:笔记:

We use Array.from() to treat the result of document.getElementsByClassName as an Array as it's returned as a Nodelist or an array-like object and doesn't have the Array properties and the .forEach method in older browsers.我们使用Array.from()document.getElementsByClassName的结果视为一个Array因为它作为Nodelist类似数组的对象返回,并且在旧浏览器中没有Array属性和.forEach方法。

Use cssText使用 cssText

 css(document.getElementById("red"),"color:red;font-size:24px") function css(el,cssText){ el.style.cssText=cssText; }
 <div id="red">something</div>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM