Add height on click with javascript

2019-08-30 06:30发布

问题:

I am having a hard time figuring out how to add height to my div. Considering this Html :

<div id='box'></div> 
<div id='plus' onClick='resize()'>add height</div>

I am using this method: - on click i read the current height of the div - after that i convert the string i get to integer - then i add some pixels to the box height

The JS looks like this:

   function resize() {
     //get element

     var height=document.getElementById('box').style.height;

     //transform element from string to integer

     height=height.replace("px","");
      height=+height;

      //change height

      var n=height;
      height=n+300+'px';        
   }

This should be pretty basic but i can't figure out what i'm missing.

回答1:

you have not to assign new height to element try below code

function resize() { 
 //get element

 var height=document.getElementById('box').style.height;

 //transform element from string to integer

 height=height.replace("px","");
  height=+height;

  //change height

  var n=height;
  height=n+300+'px';        
 document.getElementById('box').style.height = height;
}


回答2:

add this at the end of your code

document.getElementById('box').style.height = height


回答3:

See this : Sample fiddle

You missed:

    document.getElementById('box').style.height = height