简体   繁体   English

Javascript更改css(“宽度”)?

[英]Javascript change css(“width”)?

if(document.getElementById("gal").style.width = 513) {
    document.getElementById("gal").style.width = "25%";
    document.getElementById("gal").style.height = "auto";
}

I'm trying to change default width for certain image width added on Gallery. 我正在尝试为添加在图库上的某些图像宽度更改默认宽度。

This code perfectly work, the problem is that getelementbyid changed just the first element of the gallery. 这段代码可以完美地工作,问题在于getelementbyid只是更改了画廊的第一个元素。

How can i do the same, using getelementsbyclassname? 我如何使用getelementsbyclassname做同样的事情? Or are there any other way to change all of the id's style? 还是有其他方法可以更改所有ID的样式?

Thanks in advance. 提前致谢。

As you added jquery tag which means you are jquery. 当您添加了jquery标签时,这意味着您是jquery。 So if you are using jquery then why not to use jquery built-in css() function. 因此,如果您使用的是jquery,为什么不使用jquery内置的css()函数。

$(".your-class").css("width": "25%");
$(".your-class").css("height": "auto");

OR 要么

$(".your-class").css({"width": "25%", "height": "auto"});

If you actually use jQuery (you've tagged your question with it, but haven't used it anywhere), changing the width and height of all elements matching a selector is really easy using jQuery's css function : 如果您实际使用jQuery(您已经用问题标记了问题,但是没有在任何地方使用它),那么使用jQuery的css函数更改与选择器匹配的所有元素的widthheight真的很容易:

$("your-selector-here").css({
    width: "25%",
    height: "auto"
});

If you don't use jQuery, you use querySelectorAll and a loop, for instance: 如果不使用jQuery,则使用querySelectorAll和一个循环,例如:

document.querySelectorAll("your-selector-here").forEach(function(element) {
    element.style.width = "25%";
    element.style.height = "auto";
});

The NodeList returned by querySelectorAll only got the forEach method fairly recently. querySelectorAll返回的NodeList最近才获得了forEach方法。 See this answer for how to ensure that it exists on the browser you're using. 请参阅此答案以了解如何确保它在您使用的浏览器中存在。

if (document.getElementById("gal").style.width = 513) { ...

Should become 应该成为

if (document.getElementById("gal").style.width == 513) {

You missed a =. 您错过了=。

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

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