【问题标题】:onResize Event Duplicating ObjectonResize 事件复制对象
【发布时间】:2014-07-18 11:44:31
【问题描述】:

我在处理 onResize 事件时遇到了问题。我有一个 if/else 语句来检查窗口是否调整大小

<div class="author-wrap">
    <div class="the">Sample</div>
</div>

onResize:

onResize = function() {
    var responsive_viewport = $(window).width();
    if (responsive_viewport < 768) {
        $('.the').prepend('<h3>Hi</h3>');
    } else {
    }
}
$(document).ready(onResize);
$(window).bind('resize', onResize);

这里是 jsfiddle 上的代码,可以看到它的实际效果:http://jsfiddle.net/K7Ugc/1/

【问题讨论】:

  • 你在独立的 html 页面中测试过这段代码吗?

标签: javascript jquery events


【解决方案1】:

检查前置元素是否已经存在。我想到了这个棘手的方法

onResize = function() {
    var responsive_viewport = $(window).width();
    var author_page = $('.main-content.author-archive');
    var author_name = $('h3.cat-label strong').text();
    var author_wrap = $('.author-wrap');
    if (responsive_viewport < 768) {
      if (!$('.the h3').text()){
        $('.the').prepend('<h3>Hi</h3>');
      }
    } else {
    }
}
$(document).ready(onResize);
$(window).bind('resize', onResize);

【讨论】:

  • 啊,完美!正是我需要的。愚蠢的我没有想到这一点。谢谢!
【解决方案2】:

您是否希望它只运行一次?如果您希望这样做,您可以取消绑定事件:

onResize = function() {
    var responsive_viewport = $(window).width();
    var author_page = $('.main-content.author-archive');
    var author_name = $('h3.cat-label strong').text();
    var author_wrap = $('.author-wrap');
    if (responsive_viewport < 768) {
        alert(responsive_viewport);
        $('.the').prepend('<h3>Hi</h3>');
        $(window).unbind();
    } else {
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    相关资源
    最近更新 更多