js实现图片大小撑满容器,但不改变原始比例

函数代码:

function loadpic(ImgObj,width,height){
	//获取容器比例
	var rates = width/height;
	//加载图片
	var image = new Image();
	image.src = ImgObj.src;
	image.onload = function() {
		var imgWidth = image.width;
		var imgHeight = image.height;
		//获取原始图片比例
		var rate = imgWidth/imgHeight;
		if(rate >= rates){
			ImgObj.width = width
			ImgObj.height = width/rate
		}
		else if(rate < rates){
			ImgObj.height = height
			ImgObj.width = height*rates
		}
	}
}

函数调用:

loadpic(document.getElementById("容器id"),容器宽度,容器高度);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用Element-UI的走马灯(Carousel)功能来动态改变图片和容器大小,可以按照以下步骤进行: 1. 引入Element-UI的Carousel组件和样式文件 ```javascript import { Carousel, CarouselItem } from 'element-ui'; import 'element-ui/lib/theme-chalk/carousel.css'; import 'element-ui/lib/theme-chalk/carousel-item.css'; ``` 2. 在Vue组件中使用Carousel组件,并绑定数据 ```html <template> <div> <el-carousel :height="carouselHeight"> <el-carousel-item v-for="(item, index) in items" :key="index"> <img :src="item.src" /> </el-carousel-item> </el-carousel> </div> </template> <script> export default { data() { return { items: [ { src: 'https://picsum.photos/800/400/?image=1' }, { src: 'https://picsum.photos/800/400/?image=2' }, { src: 'https://picsum.photos/800/400/?image=3' }, ], carouselHeight: 400, }; }, }; </script> ``` 3. 监听窗口大小变化,动态改变容器高度和图片大小 ```html <template> <div> <el-carousel :height="carouselHeight"> <el-carousel-item v-for="(item, index) in items" :key="index"> <img :src="item.src" :style="{ width: imgWidth + 'px', height: imgHeight + 'px' }" /> </el-carousel-item> </el-carousel> </div> </template> <script> export default { data() { return { items: [ { src: 'https://picsum.photos/800/400/?image=1' }, { src: 'https://picsum.photos/800/400/?image=2' }, { src: 'https://picsum.photos/800/400/?image=3' }, ], carouselHeight: 400, imgWidth: 800, imgHeight: 400, }; }, mounted() { this.adjustSize(); window.addEventListener('resize', this.adjustSize); }, beforeDestroy() { window.removeEventListener('resize', this.adjustSize); }, methods: { adjustSize() { const containerWidth = this.$el.clientWidth; const containerHeight = Math.round(containerWidth / 2); const imgWidth = containerWidth; const imgHeight = containerHeight; this.carouselHeight = containerHeight; this.imgWidth = imgWidth; this.imgHeight = imgHeight; }, }, }; </script> ``` 以上代码中,adjustSize方法会在组件挂载后和窗口大小变化时被调用,根据当前容器的宽度来计算容器高度和图片大小,并将结果保存到data中。在模板中,使用动态绑定的方式来设置图片的宽度和高度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值