img load()方法

当图片超过设定的宽度时,让它独占一行,居中显示:


代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>图片onload事件</title>
	<script type="text/javascript" src="jquery-3.1.1.js"></script>
	<style>
		img{width: 600px;}
		.block_center{display: block; margin:0px auto;}
	</style>	
</head>
<body>
	<div>
		图片11111111111111111111111
		<img src="images/0.jpg" alt="">
		图片222222222222222222222222222
		<img src="images/1.jpg" alt="">
		图片3333333333333333333333333333
		<img src="images/2.jpg" alt="">
		图片4444444444444444444444444444
		<img src="images/3.jpg" alt="">
	</div>
	<script>
		$("img").on("load",function(){
			//console.log(this);
			//console.log(this.width);
			var img=new Image();
			img.src=this.src;
			//console.log(img);
			//console.log(img.width);
			if(img.width>=1000){					
				$(this).addClass("block_center");	
			}else{
				$(this).removeClass("block_center");
			}
		});
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/zyg1515330502/article/details/80990033
IMG