简体   繁体   English

基于窗口大小的条件固定DIV

[英]Conditionally Fixed DIV Based on Window Size

I'm trying to write a script that will fix a DIV if the screen is a certain width. 我正在尝试编写一个脚本,如果屏幕有一定宽度,该脚本将修复DIV。 This is what I have so far, but the logic is not correct and I'm not sure how to write it. 到目前为止,这是我所拥有的,但是逻辑不正确,我不确定如何编写。

var controller = new ScrollMagic();

var w = $(window).width();
if(w >= 500) {
    var sidebar = new ScrollScene()
        .triggerHook("0")
        .setPin("#sidebar-pin")
        .addTo(controller);   
}
$(window).on('resize',function(){
    if(w < 500) {
            controller.removePin("#sidebar-pin",true);
    } else {
    var sidebar = new ScrollScene()
        .triggerHook("0")
        .setPin("#sidebar-pin")
        .addTo(controller); 
  }
});

http://jsfiddle.net/gtowle/jxoewzoo/ http://jsfiddle.net/gtowle/jxoewzoo/

The logic I'm aiming for is: 我想要的逻辑是:

  1. On page load, if the the window width is greater than 500, do A. If not, do nothing. 在页面加载时,如果窗口宽度大于500,则执行A。否则,不执行任何操作。
  2. On window resize, if the window width becomes less than 500, do B, and if it becomes greater than 640, do A. 调整窗口大小时,如果窗口宽度小于500,请执行B,如果窗口宽度大于640,请执行A。

I think my problem is that I'm not sure how to trigger #2 once the window is resized. 我认为我的问题是,我不确定在调整窗口大小后如何触发#2。

The first problem is that you only calculated the window's width once (on page load). 第一个问题是您只计算了一次窗口的宽度(在页面加载时)。
It isn't updated, once you resized. 调整大小后不会更新。
That's why the whole resize logic doesn't have any effect. 这就是为什么整个调整大小逻辑都没有任何作用的原因。

Another mistake you made was calling the removePin method on the controller. 您犯的另一个错误是在控制器上调用removePin方法。
It's a scene method. 这是一种场景方法。

Lastly your logic would create a new scene every time instead of updating the existing one. 最后,您的逻辑每次都会创建一个新场景,而不是更新现有场景。

So here's how you properly achieve your desired logic: 因此,这是您正确实现所需逻辑的方法:

var controller = new ScrollMagic();

var sidebar = new ScrollScene({triggerHook: 0})
    .addTo(controller);

// page load
if($(window).width() >= 500) {
    sidebar.setPin("#sidebar-pin");
}

// resize
$(window).on('resize',function(){
    var w = $(window).width();
    if(w < 500) {
        sidebar.removePin("#sidebar-pin",true);
    } else if (w >= 640) {
        sidebar.setPin("#sidebar-pin");
    }
});

And here's your fiddle: http://jsfiddle.net/jxoewzoo/1/ 这是您的小提琴: http : //jsfiddle.net/jxoewzoo/1/

hope this helps, 希望这可以帮助,
J Ĵ

Instead use css mediaqueries for something like this. 而是将CSS媒体查询用于此类操作。

The js code for onscroll: 用于onscroll的js代码:

var otherwise = true
if(w < 500) {
        Do B;
        otherwise = false;
}
if(w > 640) {
        Do A;
        otherwise = false;
}
If(otherwise) {
     var sidebar = new ScrollScene()
    .triggerHook("0")
    .setPin("#sidebar-pin")
    .addTo(controller); 
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM