简体   繁体   中英

Javascript, change width by height

I have a div whose width and height should be the same:

<div class="radior" id="ha" style="background-color: #006;" onClick='foo()'></div>

So with Javascript I first check the height and then want to change the width of the <div>

function foo(){
    var innerHeight = document.getElementById('ha').offsetHeight;
    var ele = document.getElementsByClassName("radior");

    for (var i = 0, len = ele.length; i < len; i++){
       ele[i].style.width = innerHeight;
    }
}

But somehow it wont work! I dont get it! Greetings from Germany and here is the example on fiddle:

http://jsfiddle.net/TSk6y/1/

Why dont you keep it simple? You don't need a for loop for that. Just address the element directly and append +"px" to your width declaration.

<div class="radior" id="ha" style="background-color: #006;" onClick='foo(this)'></div>

function foo(that){
    var innerHeight = that.offsetHeight;
    that.style.width = innerHeight+"px";
}

or even shorter:

function foo(that){
    that.style.width = that.offsetHeight+"px";
}

做这个

ele[i].style.width = innerHeight + "px";

Try ele[i].style.width = innerHeight+"px";

Fiddle link: http://jsfiddle.net/opherv/57V5b/

This seems to work for me - Not sure why the jsFiddle doesn't, but if I place all of your code into a .html file, and run in a standard browser (using chrome here), it works. I click on the div, and it DOES, in fact change the width:

<html>
<head>
<style>
body,html {width:100%;
    height:100%;
}

.radior{
    width: 20%;
    height: 60%;
}
</style>
</head>
<body>
<div class="radior" id="ha" style="background-color: #006;" onClick="foo()"></div>
</body>
<script type="text/javascript">
function foo(){
    var innerHeight = document.getElementById('ha').offsetHeight;
    var ele = document.getElementsByClassName("radior");

    for (var i = 0, len = ele.length; i < len; i++){
    ele[i].style.width = innerHeight;
    }
}
</script>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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