jQuery窗口调整大小

时间:2010-05-13 08:51:42

标签: javascript resize

我有一段javascript代码,应在浏览器窗口调整大小时处理

resize.style.marginRight=(resize.offsetWidth-$(this)[0].offsetWidth)+'px'

尝试这些东西(不起作用):

window.onresize = function(event) {
resize.style.marginRight=(resize.offsetWidth-$(this)[0].offsetWidth)+'px'
}

完整代码可用 - http://jsbin.com/adelu3/2/(参见页面来源)

Html(由脚本生成):

<div class="resizable-textarea">
    <span>
        <textarea class="resizable processed" cols="" rows=""></textarea>
        <div class="resize"></div>
    </span>
</div>

感谢。

2 个答案:

答案 0 :(得分:1)

$(this)[0].offsetWidth

offsetWidth是元素的属性。在window.onresize的回调代码中,thisWindow,没有offsetWidth。

this应该是什么? (链接代码中不存在onresize事件。)如果要阅读窗口宽度,请使用$(window).width()

如果要读取封闭范围中作为this的其他(祖先?)元素的宽度,则必须通过查找resize元素找到该元素,或保留对闭包中其他元素的引用,例如:

var that= this;
$(window).resize(function() {
    resize.style.marginRight= resize.offsetWidth-that.offsetWidth+'px'
});

(nb。$(this)[0]完全没有。)

答案 1 :(得分:0)

自己做。

这是一个混合的解决方案,它分享@ bobince的代码和我自己的代码。

var tarea= this;
function resize_width(){ resize.style.width= tarea.offsetWidth+'px'}
resize_width();
$(window).resize(function() {resize_width()});
相关问题