我在創建可靠的jquery代碼時將圖像調整爲其父div的寬度時遇到了非常不好的問題。有時候它有時候不工作。起初我認爲IE瀏覽器只是在竊聽我,但有時候Safari瀏覽器,Firefox或Chrome瀏覽器並沒有啓動我的方法。jQuery數據()方法不總是工作?
$(".post-body img").each(function() {
$(this).data('width', $(this).width());
$(this).data('height', $(this).height());
});
我保存寬度和高度寬度的數據方法在我的window.load - 函數。
之後,我打電話給setimgwidth()函數。
function setimgwidth() {
var bw = $('.post-body').width();
$(".post-body img").each(function() {
if (bw < $(this).data('width')) {
$(this).attr('width', Math.round(bw));
//calculate ratio height
var newHeight = (bw/$(this).data('width')) * $(this).data('height');
$(this).attr('height', Math.round(newHeight));
}
});
}
所以我檢查父div是否比它裏面的圖像小,圖像應該調整到父div的寬度。
我只是找不到,爲什麼這種方法不總是工作。有時圖像會調整大小,有時不會。
你有什麼奇怪的嗎?什麼你會做得更好? 其他一些方法?
謝謝
編輯:而在另一
jQuery(function($){//document ready
$(window).load(function(){
//Save the original image width
$(".post-body p img, .post-body .wp-caption img").each(function() {
$(this).data('width', $(this).width());
$(this).data('height', $(this).height());
});
//window resize event
$(window).resize(function() {
setimgwidth();
});
//set image width inside of .post-body
function setimgwidth() {
$(".post-body p img, .post-body .wp-caption img").each(function() {
console.debug($(this).data('width'));
console.debug($(this).data('height'));
});
}
//call image-resize functions onload
setimgwidth();
});
});//document ready
控制檯總是告訴我,圖像的寬度和高度爲0
是'setimgwidth'也被調用'window.load'? – Emmett 2010-12-18 17:21:28
是的!如果我使用console.debug($(this).data('width'));有時它是0,有時它是真正的大小。我只是不明白爲什麼它不總是工作。我想知道是否有更好的辦法,我想要什麼? – matt 2010-12-18 18:28:35