用jquery等比例控制图片宽高的具体实现 - Web前端
作者:98wpeu发布时间:2026-07-18分类:网页前端技术浏览:2
导读:核心代码:$(function(){$(".dvcontentimg").each(function(){varmaxwidth=520;if($(...
核心代码:
$(function() {
$(".dvcontent img").each(function() {
var maxwidth = 520;
if ($(this).width() > maxwidth) {
var oldwidth = $(this).width();
var oldheight = $(this).height();
var newheight = maxwidth/oldwidth*oldheight;
$(this).CSS({width:maxwidth+"px",height:newheight+"px",cursor:"pointer"});
$(this).attr("title","点击查看原图");
$(this).click(function(){window.open($(this).attr("src"))});
}
});
});
如果上面的代码不能执行,可以使用下面的代码:
$(window).load(function() {
$(".dvcontent img").each(function() {
var maxwidth = 600;
if ($(this).width() > maxwidth) {
var oldwidth = $(this).width();
var oldheight = $(this).height();
var newheight = maxwidth/oldwidth*oldheight;
$(this).css({width:maxwidth+"px",height:newheight+"px",Cursor:"pointer"});
$(this).attr("title","点击查看原图");
$(this).click(function(){window.open($(this).attr("src"))});
}
});
});
通过css还有一种方法兼容IE6能让图片在超过规定的宽度时自动按比例缩小,但该写法不符合W3C标准。代码如下:
.cate img{
max-width: 600px;
height:auto;
width:Expression(this.width > 600 ? "600px" : this.width);
}
所以在做到尽量兼容ie和其他浏览器以及符合W3C的标准下就通过JS来控制图片的宽度了,下面使用JQuery控制图片显示时的最大宽度,主代码如下:
$(window).load(function() {
$(".cate img").each(function() {
var maxwidth = 600;
if ($(this).width() > maxwidth) {
$(this).width(maxwidth);
}
});
});
代码很简单,就是cate样式下的所以img的最大宽度只能为600px。.each(function(){......}),each在这里是对指定的图片集合对象逐一调用下面的方法。这种jQuery方法在IE6及以上浏览器和Chrome及firefox上都能实现控制图片显示时的最大宽度。
相关推荐
- append和appendTo的区别以及appendChild用法 - Web前端
- 移动节点的jquery代码 - Web前端
- 3种Jquery限制文本框只能输入数字字母的方法 - Web前端
- jquery中get,post和ajax方法的使用小结 - Web前端
- jquery submit ie6下失效的原因分析及解决方法 - Web前端
- Jquery通过Ajax方式来提交Form表单的具体实现 - Web前端
- JQuery中$.ajax()方法参数详解及应用 - Web前端
- jQery使网页在显示器上居中显示适用于任何分辨率 - Web前端
- jquery隐藏标签和显示标签的实例 - Web前端
- jQuery ajax dataType值为text json探索分享 - Web前端
- 网页前端技术排行
-
- 1[Web前端]用javascript实现默认图片替代未显示的图片 - Web前端
- 2分析Iconfont-阿里巴巴矢量常用图标库 - Web前端
- 3基于jquery的滚动条滚动固定div(附演示下载) - Web前端
- 4【第六章】Foundation之按钮和下拉功能 - Web前端
- 5jQuery编写widget的一些技巧分享 - Web前端
- 6jQuery实例教程:制作网页中可折叠的面板 - Web前端
- 7在Mac/PC上远程调试iPhone/iPad上的网页 - Web前端
- 8分享精心挑选的12款优秀jQuery Ajax分页插件和教程 - Web前端
- 9jQuery实现鼠标移到元素上动态提示消息框效果 - Web前端
- 最近发表
-
- WordPress随机显示特色图片插件:Random Post Thumbnails
- KeePass实现Chrome浏览器自动填充密码方法一
- LNMP一键包nginx 301强制跳转到https教程
- KeePass实现Chrome浏览器自动填充密码方法二
- #建站# 免费的VPS管理软件Xshell8/Xftp8中文版下载
- 使用Xshell 8连接VPS教程_电脑登录vps的方法
- WordPress评论界面添加烟花????效果
- 不同浏览器书签同步方案:坚果云+Floccus_详细使用教程
- iOS端KeePassXC客户端APP:Strongbox Password Safe
- 给WordPress评论中的Gravatar头像图片添加ALT属性


