如何在响应式设计中调用不同的 jquery 动作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11387391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:33:49  来源:igfitidea点击:

how to call different jquery actions in responsive design

jqueryresponsive-design

提问by felixaburg

I'm at the point to convert my project into an responsive design.

我正在将我的项目转换为响应式设计。

What is the most handy and universal solution do you suggest to implement different jQuery-blocks for each breakpoint?

您建议为每个断点实现不同的 jQuery 块的最方便和通用的解决方案是什么?

I want to keep all scripts in one file cause of number of http-requests.

由于 http 请求的数量,我想将所有脚本保存在一个文件中。

That's what I've found:

这就是我发现的:

My problem is, they all define callbacks, but I don't know how to bind or cancel any jQuery event-listeners in these cases.

我的问题是,它们都定义了回调,但我不知道在这些情况下如何绑定或取消任何 jQuery 事件侦听器。

e.g. I have:

例如我有:

$('#selector').click( function() {
    alert('selector clicked');
});

but that should only happen if in max-width of 320px. In screen-sizes above that the click should return false or perform any other action

但只有在最大宽度为 320 像素时才会发生这种情况。在上面的屏幕尺寸中,点击应返回 false 或执行任何其他操作

at the moment, I don't have a clue how to accomplish this.

目前,我不知道如何实现这一点。

回答by elclanrs

You can just create your own breakpoints in JS. Something like this. Adjust to your needs.

您可以在 JS 中创建自己的断点。像这样的东西。根据您的需要进行调整。

var isBreakPoint = function (bp) {
    var bps = [320, 480, 768, 1024],
        w = $(window).width(),
        min, max
    for (var i = 0, l = bps.length; i < l; i++) {
      if (bps[i] === bp) {
        min = bps[i-1] || 0
        max = bps[i]
        break
      }
    }
    return w > min && w <= max
}

// Usage
if (isBreakPoint(480)) { ... } // Breakpoint between 320 and 480

回答by casraf

$('#selector').click(function() {
    if (parseInt($(window).width()) < 320) {
        ...
    }
});

回答by dhaupin

I messed around with some libraries and stuff and ended up using this kind of responsive listener. It uses CSS media queries for breakpoints and UnderscoreJS for a throttler. The advantage I see is that the breakpoints are all defined in CSS instead of fragmented around various scripts.

我弄乱了一些库和东西,最终使用了这种响应式侦听器。它对断点使用 CSS 媒体查询,对节流器使用 UnderscoreJS。我看到的优点是断点都是在 CSS 中定义的,而不是围绕各种脚本进行碎片化。

Example CSS @mediabreakpoints using :afteron the body:

在 上@media使用的示例 CSS断点::afterbody

body:after {
    content: 'widescreen';
    display: none;
}
@media screen and (max-width: 1024px){
    body:after {
        content: "extra-large";
    }
}
@media screen and (max-width: 768px){
    body:after {
        content: "large";
    }
}
@media screen and (max-width: 640px){
    body:after {
        content: "medium";
    }
}
@media screen and (max-width: 480px){
    body:after {
        content: "small";
    }
}
@media screen and (max-width: 320px){
    body:after {
        content: "tiny";
    }
}

Example listener script waiting to fire based on content of body:after. As you can see it's defined as 2 ranges in this example for show/hide/move/create widgets based on device generality:

等待基于 的内容触发的示例侦听器脚本body:after。如您所见,在此示例中,它被定义为 2 个范围,用于基于设备通用性的显示/隐藏/移动/创建小部件:

<script type ="text/javascript">
$(window).resize(_.debounce(function(e){
    var size = window.getComputedStyle(document.body,':after').content.replace(/"|'/g, ''),
        mobile = ["tiny", "small", "medium", "large"].indexOf(size),
        desktop = ["extra-large", "widescreen"].indexOf(size);

    $('.placehold').html('computed breakpoint: ' + size + '<br />mobile index = ' + mobile + '<br />desktop index = ' + desktop);

    if (mobile != -1) {
        $('.placehold2').html('mobile range');
    } else if (desktop != -1) {
        $('.placehold2').html('desktop range');
    }
}, 100)).trigger('resize');
</script>

http://jsfiddle.net/Dhaupin/nw7qbdzx/- Just resize the output pane in jsfiddle to test it out.

http://jsfiddle.net/Dhaupin/nw7qbdzx/- 只需调整 jsfiddle 中输出窗格的大小即可进行测试。

EDIT:Apparently browsers render the :after contents via window.getComputedStyle(document.body,':after').contentdifferently and insert either single or double quotes. Added a replace to scrub them out.

编辑:显然浏览器通过window.getComputedStyle(document.body,':after').content不同的方式呈现 :after 内容并插入单引号或双引号。添加了一个替换来擦掉它们。

回答by JacobLett

If you are using Bootstrap 4 you can use this jQuery plugin to check what breakpoint is set by checking the CSS display property of elements.

如果您使用的是 Bootstrap 4,您可以使用这个 jQuery 插件通过检查元素的 CSS 显示属性来检查设置的断点。

https://jacoblett.github.io/IfBreakpoint/

https://jacoblett.github.io/IfBreakpoint/

Then use it like

然后像这样使用它

if ( xs == true ) { 
  alert("mobile first");
}

// Update on window resize
$( window ).resize( function(){
  $("h2").text( breakpoint ); 
}); 

回答by Black

You can try my solution:

你可以试试我的解决方案:

// Example for your Request
var clickCounter = 0;

$('#selector').click( function() {
    if (ifMaxWidth(320)) {
        console.log('selector clicked #'+ clickCounter++ +" times");
    }
});

// More examples
bpChecks();
$(window).on("orientationchange resize", function(event) { bpChecks(); });

function bpChecks()
{
    ifMinWidth(992, function() {
        console.log("hello from callback 1");
    });
    
    ifMaxWidth(1199, function() {
        console.log("hello from callback 2");
    });
    
    ifBetweenMinAndMaxWidth(992, 1199, function() {
        console.log("hello from callback 3");
    });
}


// Methods
function ifBetweenMinAndMaxWidth(minWidth, maxWidth, callback)
{
    var w = $(window).width();

    var result = w < maxWidth && w > minWidth;
    if (result) {
        console.log("width ("+ w +") is between "+ minWidth + " and " + maxWidth);
        if (callback !== undefined) { callback(); }
    } else {
        console.log("width ("+ w +") is NOT between "+ minWidth + " and " + maxWidth);
    }
    return result;
}

function ifMinWidth(minWidth, callback)
{
    var w = $(window).width();

    var result = w > minWidth;
    if (result) {
        console.log("width ("+ w +") is greater than "+ minWidth);
        if (callback !== undefined) { callback(); }
    } else {
        console.log("width ("+ w +") is NOT greater than "+ minWidth);
    }
    return result;
};

function ifMaxWidth(maxWidth, callback)
{
    var w = $(window).width();

    var result = w < maxWidth;
    if (result) {
        console.log("width ("+ w +") is smaller than "+ maxWidth);
        if (callback !== undefined) { callback(); }
    } else {
        console.log("width ("+ w +") is NOT smaller than "+ maxWidth);
    }
    return result;
};
#selector { 
  display: flex; 
  align-items: center; 
  justify-content: center; 
  align-content: center;
  background: blue; 
  width: 250px; 
  height: 250px; 
}
#selector:hover { cursor:pointer; }
#selector p { color: white; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="selector">
    <p>Click me</p>
</div>

回答by Matty J

If you are targeting modern browsers (IE10 upwards, and not IE mobile), then you should use the new window.matchMedia()method, as discrepancies between all the various browsers as to how they measure scrollbar width means that if you use for example window.width(), there will be a small range of pixels where the CSS behaves differently to the JS (I found this out the hard way).

如果您的目标是现代浏览器(IE10 向上,而不是 IE 移动),那么您应该使用新window.matchMedia()方法,因为所有不同浏览器之间关于它们如何测量滚动条宽度的差异意味着如果您使用例如window.width(),将会有一个小范围的像素,其中 CSS 的行为与 JS 不同(我发现这一点很困难)。

This article goes in to further details: https://www.fourfront.us/blog/jquery-window-width-and-media-queries

本文详细介绍:https: //www.fourfront.us/blog/jquery-window-width-and-media-queries

Use something like the following so that your JS and CSS work on exactly the same breakpoints:

使用类似以下内容,以便您的 JS 和 CSS 工作在完全相同的断点上:

if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide, write code specific for that */
} else {
  /* the viewport is less than 400 pixels wide, write code specific for that */
}

The Mozilla Developer Network has documented this here: https://developer.mozilla.org/en/docs/Web/API/Window/matchMedia

Mozilla 开发者网络在此处对此进行了记录:https: //developer.mozilla.org/en/docs/Web/API/Window/matchMedia