![](/img/trans.png)
[英]addEventListener that onmouseover changes the src of an html img object
[英]How to edit the img src onmouseover?
在一個包含大量圖像的網站上,我想在每個圖像上添加一個mouseover事件。
我可以這樣做:
<img class="brand"
src="img/brands-grey/image1.svg"
onmouseover="this.src='img/brands/image1.svg';"
onmouseout="this.src='img/brands-grey/image1.svg';"/>
<img class="brand"
src="img/brands-grey/image2.svg"
onmouseover="this.src='img/brands/image2.svg';"
onmouseout="this.src='img/brands-grey/image2.svg';"/>`
但是我寧願從src中刪除/插入“ -grey” onmouseover / out。 有人可以告訴我如何做到這一點嗎?
提前致謝!
您將jQuery作為標記,因此這是jQuery解決方案:
$(document).ready(function(){
$('img.brand').mouseenter(function(){
$(this).attr('src', $(this).attr('src').replace('-grey', ''));
}).mouseleave(function(){
$(this).attr('src', $(this).attr('src').replace('brands', 'brands-grey'));
});
});
HTML將更加干凈:
<img class="brand" src="img/brands-grey/image1.svg" />
<img class="brand" src="img/brands-grey/image2.svg" />
我將使用現有的jQuery插件(如jQuery.BlackAndWhite)代替使用2組圖像。
嘗試這個
<img class="brand" src="img/brands-grey/image1.svg" onmouseover="this.src='img/brands/image1.svg';" onmouseout="this.src='img/brands-grey/image1.svg';"/>
<img class="brand" src="img/brands-grey/image2.svg" onmouseover="this.src='img/brands/image2.svg';" onmouseout="this.src='img/brands-grey/image2.svg';"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('img.brand').hover(function(){
// this function will be called when the mouse in
var src= $(this).attr('src');
src.replace('brands-grey', 'brands') ;
$(this).attr('src', src);
},
function (){
// mouse out handler
var src= $(this).attr('src');
src.replace('brands', 'brands-grey');
$(this).attr('src', src);
}
)
})
</script>
請更正jquery路徑的路徑。 在這里,我們使用了jQuery懸停方法。 然后jsut按照您的要求實現了從src添加/刪除灰色部分的邏輯。
您可以只使用CSS偽類:hover
並使用包含兩個圖像的任何包裝器,這將在所有情況下都有更好的表現:
HTML:
<span class="img-container">
<img class="brand" src="img/brands-grey/image1.svg"/>
<img class="brand-over" src="img/brands/image1.svg"/>
</span>
<span class="img-container">
<img class="brand" src="img/brands-grey/image2.svg"/>
<img class="brand-over" src="img/brands/image2.svg"/>
</span>
CSS:
.brand-over {
display: none;
}
.img-container:hover .brand-over {
display: inline;
}
.img-container:hover .brand {
display: none;
}
現在,如果brands-grey
只是一個變灰的圖像,您甚至不需要兩個不同的圖像,只需使用例如opacity: 0.4;
並將圖像的不透明度設置為1。jsFiddle
或在過渡中使用CSS3過濾器: jsFiddle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.