Programing

창 크기 조정의 jQuery

crosscheck 2020. 5. 22. 23:42
반응형

창 크기 조정의 jQuery


다음 JQuery 코드가 있습니다.

$(document).ready(function () {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
});

유일한 문제는 브라우저가 처음로드 될 때만 작동한다는 것입니다 containerHeight. 창 크기를 조정할 때도 확인 하고 싶습니다 .

어떤 아이디어?


다음은 jQuery, javascript 및 CSS를 사용하여 크기 조정 이벤트를 처리하는 예입니다.
(크기 조정에 대한 스타일을 지정하는 경우 가장 좋은 방법은 CSS입니다 (미디어 쿼리))
http://jsfiddle.net/CoryDanielson/LAF4G/

CSS

.footer 
{
    /* default styles applied first */
}

@media screen and (min-height: 820px) /* height >= 820 px */
{
    .footer {
        position: absolute;
          bottom: 3px;
          left: 0px;
        /* more styles */
    }
}

자바 스크립트

window.onresize = function() {
    if (window.innerHeight >= 820) { /* ... */ }
    if (window.innerWidth <= 1280) {  /* ... */ }
}

jQuery

$(window).on('resize', function(){
      var win = $(this); //this = window
      if (win.height() >= 820) { /* ... */ }
      if (win.width() >= 1280) { /* ... */ }
});

크기 조정 코드가 자주 실행되지 않도록하려면 어떻게합니까?

이것은 크기 조정을 위해 바인딩 할 때 가장 먼저 눈에 띄는 문제입니다. 사용자가 브라우저의 크기를 수동으로 조정할 때 크기 조정 코드는 LOT이라고 불립니다.

크기 조정 코드의 호출 빈도를 제한하기 위해 밑줄로우 대시 라이브러리 에서 디 바운스 또는 스로틀 방법을 사용할 수 있습니다 .

  • debounce마지막 크기 조정 이벤트 후 크기 조정 코드 X 밀리 초 만 실행합니다. 이것은 사용자가 브라우저 크기 조정을 마친 후에 크기 조정 코드를 한 번만 호출하려는 경우에 이상적입니다. 모든 크기 조정 이벤트를 업데이트하는 데 비용이 많이 드는 그래프, 차트 및 레이아웃을 업데이트하는 데 유용합니다.
  • throttleX 밀리 초마다 크기 조정 코드 만 실행합니다. 코드가 얼마나 자주 호출되는지 "스로틀"합니다. 이것은 크기 조정 이벤트와 함께 자주 사용되지는 않지만 알아 둘 가치가 있습니다.

밑줄이나 낮은 대시가없는 경우 비슷한 솔루션을 직접 구현할 수 있습니다. JavaScript / JQuery : $ (window) .resize 크기 조정이 완료된 후 실행하는 방법은 무엇입니까?


자바 스크립트를 함수로 옮긴 다음 해당 함수를 창 크기 조정에 바인딩하십시오.

$(document).ready(function () {
    updateContainer();
    $(window).resize(function() {
        updateContainer();
    });
});
function updateContainer() {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
}

jQuery에는 .resize () 창에 첨부 할 수있는 resize 이벤트 핸들러가 있습니다 . 따라서 입력 $(window).resize(function(){/* YOUR CODE HERE */})하면 창 크기를 조정할 때마다 코드가 실행됩니다.

따라서 원하는 것은 첫 번째 페이지로드 후 및 창 크기를 조정할 때마다 코드를 실행하는 것입니다. 따라서 코드를 자체 함수로 가져 와서 두 경우 모두 해당 함수를 실행해야합니다.

// This function positions the footer based on window size
function positionFooter(){
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    else {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    } 
}

$(document).ready(function () {
    positionFooter();//run when page first loads
});

$(window).resize(function () {
    positionFooter();//run on every window resize
});

참조 : 크로스 브라우저 창 크기 조정 이벤트 - 자바 스크립트 / jQuery를


Try this solution. Only fires once the page loads and then during window resize at predefined resizeDelay.

$(document).ready(function()
{   
   var resizeDelay = 200;
   var doResize = true;
   var resizer = function () {
      if (doResize) {

        //your code that needs to be executed goes here

        doResize = false;
      }
    };
    var resizerInterval = setInterval(resizer, resizeDelay);
    resizer();

    $(window).resize(function() {
      doResize = true;
    });
});

Give your anonymous function a name, then:

$(window).on("resize", doResize);

http://api.jquery.com/category/events/


can use it too

        function getWindowSize()
            {
                var fontSize = parseInt($("body").css("fontSize"), 10);
                var h = ($(window).height() / fontSize).toFixed(4);
                var w = ($(window).width() / fontSize).toFixed(4);              
                var size = {
                      "height": h
                     ,"width": w
                };
                return size;
            }
        function startResizeObserver()
            {
                //---------------------
                var colFunc = {
                     "f10" : function(){ alert(10); }
                    ,"f50" : function(){ alert(50); }
                    ,"f100" : function(){ alert(100); }
                    ,"f500" : function(){ alert(500); }
                    ,"f1000" : function(){ alert(1000);}
                };
                //---------------------
                $(window).resize(function() {
                    var sz = getWindowSize();
                    if(sz.width > 10){colFunc['f10']();}
                    if(sz.width > 50){colFunc['f50']();}
                    if(sz.width > 100){colFunc['f100']();}
                    if(sz.width > 500){colFunc['f500']();}
                    if(sz.width > 1000){colFunc['f1000']();}
                });
            }
        $(document).ready(function() 
            {
                startResizeObserver();
            });

function myResizeFunction() {
  ...
}

$(function() {
  $(window).resize(myResizeFunction).trigger('resize');
});

This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize') to run on page load instead.

UPDATE: Here's another option if you don't want to make use of any other third-party libraries.

This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).

It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.

function myResizeFunction() {
  var $window = $(this),
      height = Math.ceil($window.height()),
      previousHeight = $window.data('previousHeight');

  if (height !== previousHeight) {
    if (height < 819)
      previousHeight >= 819 && $('.footer').removeClass('hgte819');
    else if (!previousHeight || previousHeight < 819)
      $('.footer').addClass('hgte819');

    $window.data('previousHeight', height);
  }
}

$(function() {
  $(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});

As an example, you might have the following as some of your CSS rules:

.footer {
  bottom: auto;
  left: auto;
  position: static;
}

.footer.hgte819 {
  bottom: 3px;
  left: 0;
  position: absolute;
}

Use this:

window.onresize = function(event) {
    ...
}

You can bind resize using .resize() and run your code when the browser is resized. You need to also add an else condition to your if statement so that your css values toggle the old and the new, rather than just setting the new.

참고URL : https://stackoverflow.com/questions/9828831/jquery-on-window-resize

반응형