将身体放入DIV可以杀死事件

时间:2014-01-23 22:36:45

标签: javascript jquery

不要问我为什么,但我想将整个身体放入div中,并缩小内容。到目前为止我有这个:

$('#newButton').click(function() {
    if ($('#xxxx').length == 0)
    {
        $('body').html('<div id="xxxx">'+$('body').html()+'</div>');
        $('#xxxx').css('background-color', 'red').css('overflow', 'scroll');
    }
    alert ($('#xxxx').width());
    $('#xxxx').width (parseInt($('#xxxx').width())-10+'px');
});

到目前为止还可以 - 但是这个click()方法再也不会触发了。由于一个未知的原因,它被杀了......

3 个答案:

答案 0 :(得分:3)

更新.html()时,您销毁了原始DOM元素。然后,您创建了一个具有相同ID的新元素,但没有事件处理程序。 (请记住,HTML与DOM元素不同。当您删除并替换HTML时,将从该代码创建全新的DOM元素。)

您可以使用event delegation解决此问题:

$('document').on('click','#newButton',function() {

但我会改用.wrapAll()

if ($('#xxxx').length == 0) {
    $('body > *').wrapAll('<div id="xxxx">');

答案 1 :(得分:1)

试试这个:

<style>
    #xxxx{ position: absolute; top: 0px; left: 0px; background: none; display: none; }
</style>

$('#newButton').click(function() {
    if ($('#xxxx').length == 0)
    {
        $('body').append('<div id="xxxx">'+$('body').html()+'</div>');
        $('#xxxx').css('background-color', 'red')
          .css('overflow', 'scroll')
          .css("display", "block";
    }
    alert ($('#xxxx').width());
    $('#xxxx').width (parseInt($('#xxxx').width())-10+'px');
});

这将在旧体顶部复制一个新的“身体”(实际上它是一个具有相同内容的div)。

答案 2 :(得分:0)

为什么我想要它(它可能很奇怪,但我们程序员必须习惯于奇怪的解决方案)。 我想简化以缩小窗口检查网站,所以用 - 和+你可以减少/增加“窗口”:

$(document).ready(function() {

var doResizing = function (increaseWith)
{
    if ($('#xxxx').length == 0)
    {
        $('body').css('margin', 0).css('padding', 0);
        $('body > *').wrapAll('<div id="xxxx" /></div>');
        $('#xxxx').css('background-color', 'red').css('overflow', 'scroll').css('padding', 0).css('margin', 0).css('position', 'absolute').width('100%');
    }
    $('#xxxx').height(parseInt($(window).height())+'px').width(parseInt($('#xxxx').width())+increaseWith+'px');
}

$(document).keypress(function(e) {
    if (e.which == 45) { doResizing (-10); }
    if (e.which == 43) { doResizing (+10); }
});

});

享受!

相关问题