[英]How to Change a div width when size of browser window change with javascript
How to Change a div width when size of browser window change with javascript (no jQuery)? 使用JavaScript(无jQuery)更改浏览器窗口大小时,如何更改div宽度? I want to perform this job dynamically when user resize his browser.
我想在用户调整浏览器大小时动态地执行此作业。 Please help, Immediately ... any suggestion for this job with css?
请帮助,立即...对CSS进行这项工作有什么建议吗?
Use percentage. 使用百分比。 for example
width="50%"
This will change the width when browser size change. 例如
width="50%"
这将在浏览器大小更改时更改宽度。
You can either set this with CSS or Javscript 您可以使用CSS或Javscript进行设置
CSS would be easily done using %'s ie 使用%s即可以轻松完成CSS
div {
width: 95%;
}
JS would be easily done using 使用JS可以轻松完成
var element = document.getElementById("x");
window.addEventListener('resize', function(event) {
element.style.width = window.style.width;
});
This code should work in all browsers. 此代码应在所有浏览器中都有效。 But you really should use CSS instead.
但是您确实应该使用CSS代替。
<!DOCTYPE html >
<html>
<head>
<meta charset="utf8" />
<title>untitled</title>
</head>
<body>
<div id="myDiv" style=" height: 200px; margin:10px auto; background: green;"></div>
<script type="text/javascript">
var myElement = document.getElementById('myDiv');
function detectWidth(){
var myWidth = 0;
if(typeof (window.innerWidth)== 'number'){
myWidth = window.innerWidth;
}
else {
myWidth = document.documentElement.clientWidth; //IE7
}
myElement.style.width=myWidth-300+'px';
}
window.onload=function(){
detectWidth();
};
window.onresize = function (){
detectWidth();
};
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.