用jquery等比例控操控图片宽高的具体实现
发布时间:2023-10-04 14:26:32 所属栏目:教程 来源:
导读:核心代码:
$(function() { $(".dvcontent img").each(function() { var maxwidth = 520; if ($(this).width() > maxwidth) { var oldwidth = $(this).width(); var oldheight = $(this).height(); var newheigh
$(function() { $(".dvcontent img").each(function() { var maxwidth = 520; if ($(this).width() > maxwidth) { var oldwidth = $(this).width(); var oldheight = $(this).height(); var newheigh
核心代码: $(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上都能实现控制图片显示时的最大宽度。 (编辑:聊城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐