gpt4 book ai didi

javascript - 基于窗口宽度 jquery 执行函数的替代方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:51 24 4
gpt4 key购买 nike

我试图在宽度 <450 时显示按钮并隐藏内容,如果 >450,则执行切换方式,隐藏按钮并显示内容。使用 css 代码隐藏和显示没有问题,但问题是一旦我单击 <450 中的按钮,这些东西就会显示出来,如果我返回 >450 屏幕,该按钮将不会再次隐藏。我曾尝试将 window.resize 放在 jquery 中,它给我带来了奇怪的性能。单击运行代码以查看它。欣赏。

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 条件来验证窗口宽度,因为只有当窗口小于 450 像素时才能访问按钮。

删除它,它就可以工作了。

Try this DEMO

j查询代码:

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();

}
});

关于javascript - 基于窗口宽度 jquery 执行函数的替代方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29496190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com