简体   繁体   English

添加类宽度的js代码不起作用

[英]js code for adding width of a class is not working

I want to change the width by adding 20%. 我想通过添加20%来更改宽度。 My div class width in percentage. 我的div类宽度(以百分比为单位)。 For example i have div with width 20%. 例如,我的div宽度为20%。 I am using class name for stylesheet. 我正在为样式表使用类名。 When each time the page loading it want increase by 10%. 每次页面加载时,它希望增加10%。 The code is shown below. 代码如下所示。 the avascript code document.getElementsByClassName("box")[0].style.width; 头像代码document.getElementsByClassName("box")[0].style.width; is not working` proper. 无法正常运作。 Please help me. 请帮我。

html html

<div class="box">

 var width = document.getElementsByClassName("box")[0].style.width; var n = width + 20%; width = n; 
 .box{ width:40%; height:300px; background-color:red; } 
 <div class="box"> </div> 

This line has a syntax error 这行语法错误

width + 20%; 宽度+ 20%;

If you want to calculate percentage then 如果要计算百分比

width = width + width*20/100;

Edit 编辑

As @Rory pointed out in the comments, your width value isn't getting set because width value isn't getting fetched correctly at first place, here is the updated code 正如@Rory在评论中指出的那样,您的宽度值未设置,因为宽度值最初没有正确获取,这是更新的代码

var ele = document.getElementsByClassName("box")[0];
var width = parseInt(window.getComputedStyle(ele).width); //get computed style instead of style property
width = width + width*20/100;
document.getElementsByClassName("box")[0].style.width = width;

Edit 2 编辑2

As pointed out by @Anant, if you want to increase with in percentage, then 正如@Anant指出的那样,如果您想增加百分比,则

var fn = (elem) => ((elem.offsetWidth/(elem.offsetParent || elem).offsetWidth)*100).toFixed(2)+'%' ;
var ele = document.getElementsByClassName("box")[0];
var width = parseInt(fn(ele)); //get computed style instead of style property
console.log(width);
//width = width + width*20/100;
width = (width + 20) + "%";
console.log(width);
document.getElementsByClassName("box")[0].style.width = width;

Demo 演示

 var fn = (elem) => ((elem.offsetWidth/(elem.offsetParent || elem).offsetWidth)*100).toFixed(2)+'%' ; var ele = document.getElementsByClassName("box")[0]; var width = parseInt(fn(ele)); //get computed style instead of style property console.log(width); //width = width + width*20/100; width = (width + 20) + "%"; console.log(width); document.getElementsByClassName("box")[0].style.width = width; 
 .box{ width:40%; height:300px; background-color:red; } 
 <div class="box"> </div> 

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

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