因此,我试图做到这一点,因此每按一次按钮,圆圈就会变宽。我遇到了最奇怪的问题,它们是一段代码,当您将其放在alert()方法中时,它可以正确显示,但是如果将其放入变量然后显示,则显示为nul。这是完整的代码。
<!doctype html>
<html>
<head>
<title>CSS Basics</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
#circle {
width:200px;
height:200px;
border-radius:200px;
background-color:red;
}
</style>
</head>
<body>
<div id="circle">asdfasdf</div>
<button id="Saver"> Press me to save your text </button>
<input id="Text" type="text" value="test"/>
<script type="text/javascript">
var divId="circle";
var obj= document.getElementById("Saver");
var it234 = 1;
//THIS IS A COMMENT DOESNT THSI MAKE YOU HAPPY
obj.onclick=function() {
document.getElementById("circle").innerHTML = document.getElementById("Text").value;
it234 = parseInt(document.getElementById("circle").style.width.substring(0,3));
//document.getElementById("circle").style.width="300px";
alert(it234);
}
</script>
</body>
</html>
这是正在进行的部分
这应该可以,但是不能
obj.onclick=function() {
document.getElementById("circle").innerHTML = document.getElementById("Text").value;
it234 = parseInt(document.getElementById("circle").style.width.substring(0,3));
//document.getElementById("circle").style.width="300px";
alert(it234);
}
但是,如果不进行操作,它会向Nan发出警报。如何将这个div的宽度保存到变量中(最好是字符串格式)?
最佳答案
Javascript element.style
仅返回内联样式,而不返回样式表或样式标签中设置的样式,因此document.getElementById("circle").style.width
不返回任何内容,仅返回一个空字符串,并将其解析为整数则返回NaN
(不是数字)。
使用getComputedStyle
可以代替计算样式
var divId = "circle";
var obj = document.getElementById("Saver");
var it234 = 1;
obj.addEventListener('click', function() {
document.getElementById("circle").innerHTML = document.getElementById("Text").value;
console.log(document.getElementById("circle").style.width)
var elem = document.getElementById("circle");
var style = window.getComputedStyle(elem);
var width = style.getPropertyValue('width');
it234 = parseInt( width.replace(/\D/g,'') );
alert(it234);
}, false);