I used the below code, but it seems not correct.I want cut the around of photo, and show only the center 200*200px, how to modify? thanks
<div style="width:200px;height:200px;overflow:hidden;background-color:#000;"><img src="http://www.chlorischile.cl/alternanthera/foto6inflorescencia.jpg" width="200"
onload="this.style.backgroundPosition=(200-image.width)/2+'px';this.style.backgroundPosition=(200-image.width)/2+'px';no-repeat;" /></div>
Thanks, it works well.
That is a great code
:-}
Let’s unpack what you’ve done there, and figure out how to get it working.
Unpacking:
#photo {
width: 200px;
height: 200px;
overflow: hidden;
background-color: #000;
}
<div id="photo">
<img src="http://www.chlorischile.cl/alternanthera/foto6inflorescencia.jpg" width="200" />
</div>
var div = document.getElementById('photo');
div.onload = "this.style.backgroundPosition=(200-image.width)/2+'px';this.style.backgroundPosition=(200-image.width)/2+'px';no-repeat;";
Let’s get rid of the onload, and instead run the script from just before the </body> tag.
You can see that the onload code was partly duplicated, and that the no-repeat is kind of just left hanging there.
Let’s fix that.
var div = document.getElementById('photo');
var image = div.getElementsByTagName('img')[0];
image.style.backgroundPosition = (200 - image.width) / 2 + 'px no-repeat';
That seems better. Now we can put it in a test page and see what happens.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
body {
background: gray;
}
#photo {
width: 200px;
height: 200px;
overflow: hidden;
background-color: #000;
}
</style>
</head>
<body>
<div id="photo">
<img src="http://www.chlorischile.cl/alternanthera/foto6inflorescencia.jpg" width="200" />
</div>
<script type="text/javascript">
var div = document.getElementById('photo');
var image = div.getElementsByTagName('img')[0];
image.style.backgroundPosition = (200 - image.width) / 2 + 'px no-repeat';
</script>
</body>
</html>
That works well.