css问题笔记2

1.在html让高度始终是宽度的一半:

1)思路:

(1)用dom求得当前的offsetWidth

(2)将宽度设定为width的一半

2)代码

<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <div class="outer" id="outer">
    <div class="inner">

    </div>
  </div>
</body>
<style>
  div{
    border: 1px;
    padding: 1px;
  }
.outer{
  border: solid red 1px;
  width: 100%;
  height: 500px;

}
</style>
<script>
  //首先进来就判断长度,执行一次
  onload=()=>{
    let width=document.getElementById("outer").offsetWidth//这个长度包含了padding和bodder的长度,所以下边计算的时候要减去4
  document.getElementById('outer').style.height=((width-4)/2)+'px';//
  }
  //动态获取outer的宽度,然后让其宽度为高度的一半
  window.onresize=function(){
    let width=document.getElementById("outer").offsetWidth//这个长度包含了padding和bodder的长度,所以下边计算的时候要减去4
  document.getElementById('outer').style.height=((width-4)/2)+'px';//
   
  };

</script>
</html>

3)效果:

猜你喜欢

转载自blog.csdn.net/Handsome2013/article/details/113785975