大佬教程收集整理的这篇文章主要介绍了javascript – 保持背景图像的宽高比,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这里的问题是,我需要呈现每个保持其纵横比的图像,并将图像的呈现最大化到容器中心图像的高度或宽度.
HTML:
<div class="fotowind shadow"></div>
编辑:
.fotowind容器的初始CSS属性:
.fotowind { overflow:hidden; margin-left:10px; BACkground:#333; margin-bottom:5px; z-index:30; BACkground-position: center center !important; BACkground-repeat: no-repeat; }
根据窗口的大小动态构建属性的代码 – 我需要调整图像的大小,保持比例,即使有一些空白的空间仍然保留在两边:
jQuery的:
windowWidth = $(window).width(); windowHeight = $(window).height(); if (windowWidth <= 1200 && windowWidth > 768 || windowHeight < 900) { $('.fotowind').css('width','650px').css('height','425px'); } else if (windowWidth > 1200 || windowHeight > 900) { $('.fotowind').css('width','950px').css('height','650px'); } if (windowWidth <= 768) { $('.fotowind').css('width','450px').css('height','425px'); }
结果HTML:
<div class="fotowind shadow" style="BACkground-image: url(http://localhost/AdPictures/25/2c/c2/4c/-9/77/1-/4b/77/-b/ff/a-/57/e5/10/2b/31/b1/7516_1_xl.jpg); BACkground-size: 100%; width: 950px; height: 650px; BACkground-position: 50% 50%; BACkground-repeat: no-repeat no-repeat;"></div>
所以在这里,我使用jQuery来检测窗口的高度和宽度,因此我调整你的背景图像大小
$(window).on('resize',function() { if($(window).width() < 300) { //original idth of your BACkground image $('div.fotowind').css('BACkground-size','100% auto'); } else if($(window).height() < 300) { //original height of your BACkground image $('div.fotowind').css('BACkground-size','auto 100%'); } else { $('div.fotowind').css('BACkground-size','auto'); } });
没有CSS解决方案,因为我们没有R_298_11845@ax-width和max-height的背景大小,所以如果你正在寻找一个纯CSS的解决方案,而不是需要一个绝对定位的img标签,max-height和max-width定义为z-index设置为负,但仍然会遇到有关元素中心定位的一些问题…
在你评论之后,你说图像的尺寸将是动态的,容器会被修改.
在这里,现在的代码完全兼容您的固定宽度容器元素..你现在不需要什么,它是完全动态的,也感谢this的答案,这有助于我获取图像的高度和宽度
$(document).on('ready',function() { var image_url = $('div.fotowind').css('BACkground-image'),image; // Remove url() or in case of Chrome url("") image_url = image_url.match(/^url\("?(.+?)"?\)$/); if (image_url[1]) { image_url = image_url[1]; image = new Image(); image.src = image_url; } // just in case it is not already loaded $(imagE).load(function () { imgwidth = image.width; imgheight = image.height; if($('div.fotowind').width() < imgwidth) { $('div.fotowind').css('BACkground-size','100% auto'); } else if($('div.fotowind').height() < imgheight) { $('div.fotowind').css('BACkground-size','auto 100%'); } else { $('div.fotowind').css('BACkground-size','auto'); } }); });
几个演示说明上述代码在行动…
Demo 1(其中图像大小>比元素大小)
Demo 2(其中容器大小>图像大小)
Demo 3(图像高度>容器高度)
Demo 4(图像高度>容器高度[2])
Demo 5(图像宽度>容器宽度)
以上是大佬教程为你收集整理的javascript – 保持背景图像的宽高比全部内容,希望文章能够帮你解决javascript – 保持背景图像的宽高比所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。