简体   繁体   English

为什么这在JS中不起作用? getElementById()。style.width + = 40 +“ px”;

[英]Why this not working in JS?? getElementById().style.width += 40 + “px”;

I'm trying to write a shorthand method getElementById().style.width += 40 + "px"; 我正在尝试写一个简写方法getElementById()。style.width + = 40 +“ px”; for changing element width in DOM via JavasScript but it isn't working. 用于通过JavasScript更改DOM中的元素宽度,但无法正常工作。 Any working solutions to achieve that? 有什么可行的解决方案可以实现这一目标?

if document.getElementById(id).style.width returns "10px" 如果document.getElementById(id).style.width返回"10px"
then document.getElementById(id).style.width += 40 + "px" will be "10px40px" 然后document.getElementById(id).style.width += 40 + "px"将为"10px40px"

Shorthand assignment is not possible. 无法进行简写分配。 but you should try the following: 但是您应该尝试以下操作:

document.getElementById("div1").style.width = (parseInt(document.getElementById("div1").style.width) + 40) + "px";

Note: replace [id] with an appropriate id. 注意:用适当的ID替换[id]。

Full example code: 完整的示例代码:

<html>
<head>
<title></title>
<script type="text/javascript">
    function incrementWidth() {
        document.getElementById("div1").style.width = (parseInt(document.getElementById("div1").style.width) + 40) + "px";
    }
</script>
</head>
<body>
  <div id="div1" style="height:100px;width:40px;background-color:orange;"></div>
  <button onclick="incrementWidth();">INCREMENT</button>
</body>
</html>

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

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