[英]How to stretch image to fill div using JavaScript
我正在嘗試使用每3秒更改一次的圖像填充div。 我正在使用此JavaScript代碼:
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.png";
images[2] = "image3.png";
HTML代碼如下所示。
<div id="banner">
<img id="img"/>
</div>
如何拉伸/裁剪這些圖像以使它們填滿整個div?
#banner {
position: fixed;
top: 10%;
height:35%;
background-color:yellow;
left: 10%;
width: 90%;
}
img {
}
CSS更適合這種情況,因為調整屏幕大小是自動處理的。
object-fit: cover
with object-position
。 <div>
背景放置,並使用background-size: cover
with background-position
。 使用object-fit: cover
var images = [ "https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/30423_pets-products_january-site-flip_3-cathealth_short-tile_592x304._CB286975940_.jpg", "https://s-media-cache-ak0.pinimg.com/736x/92/9d/3d/929d3d9f76f406b5ac6020323d2d32dc.jpg", "http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg" ], x = -1; function displayNextImage() { x = (x === images.length - 1) ? 0 : x + 1; document.getElementById("img").src = images[x]; } function displayPreviousImage() { x = (x <= 0) ? images.length - 1 : x - 1; document.getElementById("img").src = images[x]; } function startTimer() { displayNextImage(); setInterval(displayNextImage, 3000); } startTimer();
#banner { position: fixed; top: 10%; height:35%; background-color:yellow; left: 10%; width: 90%; } #img { width: 100%; height: 100%; object-fit: cover; object-position: 0 25%; }
<div id="banner"> <img id="img" /> </div>
使用background-size: cover
var images = [ "https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/30423_pets-products_january-site-flip_3-cathealth_short-tile_592x304._CB286975940_.jpg", "https://s-media-cache-ak0.pinimg.com/736x/92/9d/3d/929d3d9f76f406b5ac6020323d2d32dc.jpg", "http://r.ddmcdn.com/s_f/o_1/cx_462/cy_245/cw_1349/ch_1349/w_720/APL/uploads/2015/06/caturday-shutterstock_149320799.jpg" ], x = -1; function displayNextImage() { x = (x === images.length - 1) ? 0 : x + 1; document.getElementById("banner").style.backgroundImage = "url(" + images[x] + ")"; } function displayPreviousImage() { x = (x <= 0) ? images.length - 1 : x - 1; document.getElementById("banner").style.backgroundImage = "url(" + images[x] + ")"; } function startTimer() { displayNextImage(); setInterval(displayNextImage, 3000); } startTimer();
#banner { position: fixed; top: 10%; height:35%; background-color:yellow; left: 10%; width: 90%; background-size: cover; background-position: 0 25%; }
<div id="banner"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.