用 JS 更改.css?使用变量设置动态.css属性

Alter .css with JS? Setting dynamic .css properties with variables

本文关键字:css 设置 动态 属性 变量 JS 更改      更新时间:2023-09-26

我有如下所示的内容:

<div id="left">
    left
</div>
<div id="right">
    right
</div>

具有.css属性:

#left {
    width: 60%;
    float: left
    min-height: ###
    max-height: 1000px;
}
#right {
    width: 40%;
    float: right;
    min-height: ###
    max-height: 1000px;
}

请注意 <div> CSS min-height属性的###。我想要下面这样的东西(一些伪JS):

var leftheight = document.getElementById(left);
var rightheight = document.getElementById(right);
if (leftheight.currentHeight > rightheight.currentHeight) {
    rightheight.style.min-height = leftheight.currentHeight;
} else if (rightheight.currentHeight > leftheight.currentHeight) {
    leftheight.style.min-height = rightheight.currentHeight;
}

基本上我想要:

if (current height of left > current height of right) {
    min-height of right = current height of left
} else if (current height of right > current height of left) {
    min-height of left = current height of right
} 
//ie. both left and right have the same min-heights, whichever is larger

我的Javascript是错误的,这是我刚刚正在学习的东西。有没有一种方法可以用来获得我想要的结果?

你可以这样做:

if (leftheight.currentHeight > rightheight.currentHeight) {
    rightheight.style.minHeight = leftheight.currentHeight;
} else if (rightheight.currentHeight > leftheight.currentHeight) {
    leftheight.style.minHeight = rightheight.currentHeight;
}

这实际上minHeight不是min-height.

这里不需要javascript,你可以通过添加一个带有overflow: hidden的容器,并在leftrightdivs中添加正边距和负边距来实现这一点:

<div id="container">
    <div id="left">left</div>
    <div id="right">right<br /><br /><br /><br />Foobar</div>
</div>
#container {
    width: 75%; /* amend this as required */
    overflow: hidden;
}
#left {
    width: 60%;
    float: left;
    max-height: 1000px;
    background-color: #C00;
    padding-bottom: 1000px;
    margin-bottom: -1000px;
}
#right {
    width: 40%;
    float: right;
    max-height: 1000px;
    background-color: #0C0;
    padding-bottom: 1000px;
    margin-bottom: -1000px;
}

示例小提琴

通常,javascript永远不应该仅用于布局目的。如果有人关闭了javascript,你的页面会发生什么?

你可以使用 jquery

var leftheight = $('#left').height();
var rightheight =$('#right').height();

if (leftheight > rightheight) {
    $('#right').css('min-height',leftheight+"px")
 } 
else if (rightheight > leftheight) {
    $('#left').css('min-height',rightheight + "px")
}

使用 jquery

 $(function(){ //ready function to make sure document is ready
 var $leftdiv=$('#left'),
     $rightdiv=$('#right'),
     $leftHeight=$('#left').height(),
     $rightHeight=$('#right').height();
   if ( $leftHeight > $rightHeight) {
      $rightdiv.css('min-height':$leftHeight + "px");
   } else if ( $rightHeight > $leftHeight) {
      $leftdiv.css('min-height':$rightHeight + "px");
   } 
 });