문제

I want to move an element (div) in the dom from one place to another using jQuery. I have the code working almost too well, in that it's appending my code every single time the browser is resized and then carries on until the browser crashes.

Here's my code:

$(window).resize(function() {
    var bodyWidth = $(window).width();
    if(bodyWidth < 740){
        $('.GalleryHeader').appendTo('li');
    }
});

How do I get this to only run once, so it only does the one time, and then perhaps put it back into it's original location in the dom when resizing back up over 740px.

도움이 되었습니까?

해결책

Try

jQuery(function () {
    var flag;
    $(window).resize(function () {
        var bodyWidth = $(window).width();
        console.log(bodyWidth)
        if (flag !== false && bodyWidth < 740) {
            //move the element to new location
            console.log('less')
            flag = false;
        } else if (flag !== true && bodyWidth >= 740) {
            //put it back to original location
            console.log('more')
            flag = true;
        }
    }).resize();
})

Demo: Fiddle

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top