Home > Web Front-end > JS Tutorial > body text

javascript 动态调整图片尺寸实现代码_图象特效

WBOY
Release: 2016-05-16 18:38:06
Original
975 people have browsed it

我前段时间写的一篇文章就遇到过这种事情,后来用CSS的overflow和max-width属性暂时解决了页面变形的问题。这种方法好处是简单,但坏处是会破坏某些细节的效果。

如overflow:hidden,意思是当内部元素宽度大于父框架时隐藏超出宽度的部分。这样做可能会是一些内容突然截断,被隐藏了,很对不起观众。

通过max-width属性限制文章插图最大宽度的话,需要考虑各浏览器的兼容性。IE6是不支持这个属性的,在我印象中,一些浏览器虽然支持这个属性,但图片不是等比缩放的(好像是Safari和Opera,记不清了),这样做的话对这些浏览器的用户很不公平。

因此,我最终选择的是通过JavaScript动态改变图片尺寸。这种方法对各种浏览器兼容性良好(现在应该很少人会禁用JavaScript吧?),如果换主题的话,也可以灵活地改变文章插图的最大尺寸。

方案有两个,由于我使用的主题是加载了jQuery库的,因此可以用以下代码实现:

复制代码 代码如下:

$(document).ready(function() {
$('.post img').each(function() {
var maxWidth = 100; // 图片最大宽度
var maxHeight = 100; // 图片最大高度
var ratio = 0; // 缩放比例
var width = $(this).width(); // 图片实际宽度
var height = $(this).height(); // 图片实际高度
// 检查图片是否超宽
if(width > maxWidth){
ratio = maxWidth / width; // 计算缩放比例
$(this).css("width", maxWidth); // 设定实际显示宽度
height = height * ratio; // 计算等比例缩放后的高度
$(this).css("height", height * ratio); // 设定等比例缩放后的高度
}
// 检查图片是否超高
if(height > maxHeight){
ratio = maxHeight / height; // 计算缩放比例
$(this).css("height", maxHeight); // 设定实际显示高度
width = width * ratio; // 计算等比例缩放后的高度
$(this).css("width", width * ratio); // 设定等比例缩放后的高度
}
});
});

如果不想加载jQuery库,可以用以下代码:
复制代码 代码如下:

function ResizeImage(image, 插图最大宽度, 插图最大高度)
{
if (image.className == "Thumbnail")
{
w = image.width;
h = image.height;
if( w == 0 || h == 0 )
{
image.width = maxwidth;
image.height = maxheight;
}
else if (w > h)
{
if (w > maxwidth) image.width = maxwidth;
}
else
{
if (h > maxheight) image.height = maxheight;
}
image.className = "ScaledThumbnail";
}
}

采用纯JavaScript的话,麻烦点,需要手动为图片加上class=”Thumbnail”,但最终效果是一样的。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!