基于窗口宽度jquery的函数的替代方法是什么

what is the alternate way to do a function based on window width jquery?

本文关键字:函数 是什么 方法 jquery 于窗口 窗口      更新时间:2023-09-26

当宽度<450,如果>450,切换方式,隐藏按钮并显示内容。用css代码隐藏和显示没有问题,但问题是一旦我单击<450,东西出现了,如果我回到>450屏幕,按钮将不会再次隐藏。我曾试图在jquery中放入window.resize,它给了我奇怪的性能。点击运行代码查看。非常感谢。

if ($(window).width() < 450) {
var show_stuff=$('#all_vote_menu');
var button_menu=$('#button');
     	$(button_menu).on('click', function(){
			
			$(show_stuff).show(400,'swing');
			$(button_menu).hide();
		    
		});
		
		$(document).mouseup(function (e){
	    if (!show_stuff.is(e.target) // if the target of the click isn't the container...
	        && show_stuff.has(e.target).length === 0) // ... nor a descendant of the container
	    {	
			$(show_stuff).hide(400,'swing');
			$(button_menu).fadeIn();
		
	    }
	});
  }
#button{
     display:none ;/*hide when >450px*/
     
   }
   .all_vote_menu{
      width:200px;
      height:200px;
      background:yellow;
   }
@media screen and (max-width: 450px)  {
#button{
     display:block ;/*show when <450px*/
     color:green;
   }
   .all_vote_menu{
   	display:none;/*hide when <450px*/
   }
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button" name="all_vote_show" value="Menu"/>
<div class="all_vote_menu" id='all_vote_menu'>hello</div>

您不需要if条件来验证窗口宽度,因为只有当窗口小于450px时才能访问按钮。

删除这个,它就工作了。

试试这个演示

jquery代码:

var show_stuff=$('#all_vote_menu');
var button_menu=$('#button');
        $(button_menu).on('click', function(){
            $(show_stuff).show(400,'swing');
            $(button_menu).hide();
        });
        $(document).mouseup(function (e){
        if (!show_stuff.is(e.target) // if the target of the click isn't the container...
            && show_stuff.has(e.target).length === 0) // ... nor a descendant of the container
        {   
            $(show_stuff).hide(400,'swing');
            $(button_menu).fadeIn();
        }
    });

取消宽度检查if ($(window).width() < 450) {

如果正在显示,请在中添加检查

$(document).mouseup(function (e){
    if ($(window).width() >= 450 && !show_stuff.is(e.target) ...