如果体宽最大为500px,我想添加一个按钮

时间:2017-10-17 05:58:07

标签: javascript jquery

每当我尝试调整浏览器窗口的大小时,该按钮会多次出现 ,我该如何解决这个问题。如果浏览器的大小调整为500px或更低,我想要 应该添加div,如果宽度高于500px,则应删除div。这是JS文件

iex(1)> :pubkey_cert_records.namedCurves({1, 2, 840, 10045, 3, 1, 7})
:secp256r1
iex(2)> :pubkey_cert_records.namedCurves(:secp256r1)
{1, 2, 840, 10045, 3, 1, 7}

这里从身体标签调用Sizer,如下所示

function sizer(){const mq = window.matchMedia( "(max-width:500px)" )

if(mq.matches)
{
 let loginDiv= document.createElement('div'),
     aTag = document.createElement('a');
     aTag.setAttribute('href','#');
     aTag.innerHTML="Login/Sign Up";
     loginDiv.className='login';// style in search.css
     document.getElementsByClassName('drp')[0].appendChild(loginDiv);
     loginDiv.appendChild(aTag);

}
else{
  document.getElementsByClassName("login").remove();
}
}

Picture of viewport

1 个答案:

答案 0 :(得分:2)

您可以使用媒体查询@media (max-width: 500px)根据屏幕宽度有条件地显示/隐藏按钮。没有必要将Javascript用于此类用例。



#myButton {
  display:none;
}

@media (max-width: 500px) {
  #myButton {
    display:block;
  }
}

<button id="myButton">
Click me
</button>
&#13;
&#13;
&#13;

对于JS,您可以使用$(window).on("resize",...这样的处理程序:

&#13;
&#13;
$(window).on("resize", function() {
  console.log("Resizing: ", window.innerWidth);
  if(window.innerWidth < 500) {
    $("#myButton").show();
  } else {
    $("#myButton").hide();
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="myButton">
Click me
</button>
&#13;
&#13;
&#13;

根据窗口宽度将元素动态注入DOM:

&#13;
&#13;
$(window).on("resize", function() {
  console.log("Resizing: ", window.innerWidth);
  if(window.innerWidth < 500) {
    if($("#myDiv > #myButton").length == 0) {
      var button = document.createElement("button");
      button.innerText = "Click me";
      button.id = "myButton";
    
      $("#myDiv").append(button);
    }
  } else {
    $("#myButton").remove();
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="myDiv">
  Div.
</div>
&#13;
&#13;
&#13;