开发者

jQuery window resize

I have piece of javascript code, which should process when the browser window is resized.

开发者_如何学JAVA
resize.style.marginRight=(resize.offsetWidth-$(this)[0].offsetWidth)+'px'

Tryed this stuff (doesn't work):

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

Full code available - http://jsbin.com/adelu3/2/ (see page source)

Html (generated by the script):

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

Thanks.


$(this)[0].offsetWidth

offsetWidth is a property of elements. In the callback code of window.onresize, this is a Window, which doesn't have an offsetWidth.

What is this supposed to be? (The onresize event is not present in the linked code.) If you want to read the window width, use $(window).width().

If you want to read the width of some other (ancestor?) element that you had as this in the enclosing scope, you must either find that element by looking up from the resize element, or retain a reference to the other element in a closure, eg.:

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

(nb. $(this)[0] does precisely nothing.)


Made myself.

This is a mixed solution, it shares @bobince's code and my own.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜