Javascript调整大图像大小仅适用于F5之后
Javascript resize big image only works after F5
我使用这个javascript来调整页面上一个大(5Mb(图像的大小,最大为800px:
<script type="text/javascript">
$(document).ready(function () {
$('.detailImg').each(function () {
var maxWidth = 800; // Max width for the image
var maxHeight = 800; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if (width > maxWidth) {
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if (height > maxHeight) {
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
});
});
加载页面时,不会调整图像大小。FireBug控制台上没有错误。如果我尝试用F5刷新页面,图像会被调整大小!如果我尝试Ctrl+F5,图像将返回原始大小!
问题出在哪里?为什么这个javascript只在刷新页面时有效?
document.ready()
运行时不会加载图像。document.ready()
在加载DOM时启动,但此时图像可能仍在加载中——尤其是当它们是5MB时!因此,图像的高度和宽度在脚本运行时不可用。我猜它在F5上工作,因为图像仍然是缓存的,所以加载速度足够快,以便在脚本运行时知道它们的尺寸Ctrl-F5清除图像缓存,所以在那之后,您又回到了开始的位置。
正如我在评论中所指出的,使用图像的load()
事件可能会有所帮助,但即便如此,有时它也不会正确触发。例如,一些浏览器永远不会为已经在浏览器缓存中的图像触发load()
事件(因为从技术上讲,它还没有加载…(
有几个不同的解决方法——Paul Irish的插件可能很有用;包括插件代码,然后使用类似的东西:
$('.detailImg',this).imagesLoaded(function() {
// Your existing function code
});
或者,如果您事先知道图像大小,只需在img
元素中指定即可,例如<img src="whatever" height="1200" width="1600" alt="whatever" />
。通过这种方式,jQuery将能够判断图像是否已加载的宽度和高度。
将JS代码放在"body关闭标记"之前。
希望这能有所帮助。
相关文章:
- JQueryhide()不适用于Mozzilla,但适用于Chrome
- PHP中的setcookie仅适用于localhost
- html5 drawImage适用于firefox,而不是chrome
- 提供“;onClick"适用于iPad(触摸屏)和桌面用户的默认功能
- jQuery表单验证适用于Mozilla和Internet Explorer,但不适用于Chrome或Safari
- ResolveUrl是否适用于././也
- Firebase updateChildValues适用于IOS,但不适用于Web和Android
- JavaScript警报适用于int,但不适用于string
- SQLite插件适用于Mac和Windows,但不适用于手机上的Safari
- Regex Replace仅适用于Last Match
- window.onload适用于aspx页面,但不适用于普通html
- Jquery Ajax POST不工作.适用于GET
- 画布上的自定义字体仅适用于safari
- Javascript仅适用于alert()和Debug模式
- JS适用于Firefox和Safari,但不适用于Chrome.此处'是我的网站
- Regex不适用于Firefox,但适用于Chrome
- 通过单击主菜单外部关闭子菜单'不适用于IE,但适用于Firefox&铬
- AngularJS$http.post没有'不适用于Chrome,仅适用于IE
- Javascript仅适用于jQuery mobile中的页面刷新
- Javascript调整大图像大小仅适用于F5之后