HTML-更改复选框选择的div最大宽度属性

时间:2018-12-06 11:50:28

标签: javascript html css

我有一个checkbox和一个div。如果选中checkbox,则max-width属性应减小(div的尺寸应减小),反之亦然。

function configureMarksTableWidth(checkbox) {
  var marksTable = document.getElementById("table-mark");
  alert(checkbox.checked);
  if (checkbox.checked === true) marksTable.style.maxWidth = "600px";
}
#marks-table {
  overflow-x: scroll;
  /*max-width: 600px;*/
  border-right: 1px solid #ddd;
  border-left: 1px solid #ddd;
}
<input type="checkbox" id="check" onclick="configureMarksTableWidth(this)">
<div id="marks-table" style="max-width: 900px">

方案是这样的: 如果选中checkbox,则div的宽度应为600px,而如果未选中,则div的宽度应为900px

我得到了在我的JS函数中调用的警报的结果,但是div中没有​​任何变化

3 个答案:

答案 0 :(得分:3)

我们不需要javascript就能使用

#check:checked~#marks-table{ max-width:600px; }

#marks-table {
  overflow-x: scroll;
  max-width: 900px;
  border-right: 1px solid #ddd;
  border-left: 1px solid #ddd;
}

#check:checked~#marks-table {
  max-width: 600px;
}
<input type="checkbox" id="check">
<div id="marks-table">

但是如果您仍然要使用javascript来做到这一点,那么您的javascript是正确的,您只是将错误的id放在了getElementById中,您必须将标记表而不是像表标记那样放置

var marksTable = document.getElementById("marks-table");

答案 1 :(得分:2)

您有id="marks-table",并且正在获取table-mark,这将返回Uncaught TypeError: Cannot read property 'style'的null,请在js中更改您的ID以匹配div ID。

解决方案:

function configureMarksTableWidth(checkbox) {

    var marksTable = document.getElementById("marks-table");
    if (checkbox.checked === true)  {
        marksTable.style.maxWidth = "600px"
    } else {
    //if unchecked
        marksTable.style.maxWidth = "900px"
    }
  
}
#marks-table {
      overflow-x: scroll;
      /*max-width: 600px;*/
      border-right: 1px solid #ddd;
      border-left: 1px solid #ddd;
    }
<input type="checkbox" id="check" onclick="configureMarksTableWidth(this)">
<div id="marks-table" style="max-width: 900px">

答案 2 :(得分:1)

您在table-mark中使用了getElementById,而不是marks-table。 那是错的。 所以请这样更改ID

function configureMarksTableWidth(checkbox) {
    var marksTable = document.getElementById("marks-table");
    alert(checkbox.checked);
    if (checkbox.checked === true) marksTable.style.maxWidth = "600px";
}
 #marks-table {
      overflow-x: scroll;
      /*max-width: 600px;*/
      border-right: 1px solid #ddd;
      border-left: 1px solid #ddd;
    }
    <input type="checkbox" id="check" onclick="configureMarksTableWidth(this)">
    <div id="marks-table" style="max-width: 900px">