2 回答

TA貢獻1827條經驗 獲得超8個贊
刪除所有內聯事件處理程序
添加 mouseenter 和 leave 處理程序
訪問 css 屬性
Div 沒有 URL
我還移動了預覽,不必向下滾動太遠
$(".preview").on("mouseenter",function() {
$("#image").css({"background-image": `url(${this.src})`}); // this.src is the DOM notation for the source of the image you are hovering
})
$(".preview").on("mouseleave",function() {
$("#image").css({"background-image": "" })
})
#image {
height: 500px }
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img alt="Batter is ready" class="preview" src="https://cdn.sallysbakingaddiction.com/wp-content/uploads/2017/06/moist-chocolate-cupcakes-7.jpg" height="50">
<img alt="Perfect Baking" class="preview" src="https://cdn.sallysbakingaddiction.com/wp-content/uploads/2017/06/moist-chocolate-cupcakes-6.jpg" height="50">
<img alt="Yummy yummy cup cake" class="preview" src="https://cdn.sallysbakingaddiction.com/wp-content/uploads/2017/06/moist-chocolate-cupcakes-5.jpg" height="50">
<div id="image">
Hover over an image above to display here.<br/>
</div>

TA貢獻1893條經驗 獲得超10個贊
您嘗試設置 div 的 url(不是有效屬性)。您實際上想要做的是設置 div 的背景 URL。檢查我的代碼片段以獲取正確方向的提示。
也不要在更新函數中添加另一個事件監聽器。
function upDate(previewPic) {
let newUrl = previewPic.src;
document.getElementById("image").style.backgroundImage = 'url(' + newUrl + ')';
}
function unDo(abc) {
document.getElementById("image").style.backgroundImage = 'url()';
}
#image {
width: 100px;
height: 120px;
background-size: 100px 120px;
}
<div id="image">
Hover over an image below to display here.
</div>
<img alt="Batter is ready" class="preview" width="50" height="60" onmouseout="unDo()" onmouseover="upDate(this)" src="https://cdn.sallysbakingaddiction.com/wp-content/uploads/2017/06/moist-chocolate-cupcakes-7.jpg">
<img alt="Perfect Baking" class="preview" width="50" height="60" onmouseout="unDo()" onmouseover="upDate(this)" src="https://cdn.sallysbakingaddiction.com/wp-content/uploads/2017/06/moist-chocolate-cupcakes-6.jpg">
<img alt="Yummy yummy cup cake" class="preview" width="50" height="60" onmouseout="unDo()" onmouseover="upDate(this)" src="https://cdn.sallysbakingaddiction.com/wp-content/uploads/2017/06/moist-chocolate-cupcakes-5.jpg">
添加回答
舉報