[英]Making an image change once it is clicked
我已經花了很多時間來尋找盡可能多的在線資源和stackoverflow問題,但是由於某種原因,我只是無法弄清楚。
我試圖使用CSS和圖像精靈將鏈接顯示為圖像,將其懸停並單擊后即會更改。 我玩CSS玩了很久,現在對JavaScript的研究已經太久了,我只需要有關如何使其工作的一些指導。
一旦將鼠標懸停在上面,我就設法對其進行更改,但是,我真正需要做的是單擊圖像后進行更改。 因此,從頭開始顯示播放按鈕,單擊它會顯示一個暫停按鈕,再次單擊它會顯示播放按鈕,等等。
從我所能收集的資料來看,我將需要使用JavaScript和onclick事件。 但是我不確定這將如何工作或如何與圖像精靈一起使用。
到目前為止,我的CSS看起來像這樣
.testclass .stratus { background-position: -1px -1px; width: 21px; height: 21px;}
.testclass .stratus { background-position: -1px -1px; width: 21px; height: 21px;}
。
.testclass .stratus:hover {background-position: -1px -29px; width: 21px; height: 21px;}
.testclass .stratus:hover {background-position: -1px -29px; width: 21px; height: 21px;}
。
但是,這僅會影響播放按鈕及其懸停時的播放按鈕。 現在,我需要一種方法,當單擊播放按鈕時顯示暫停按鈕,反之亦然。
圖片精靈網址。 http://www.danceyrselfclean.com/wp-content/uploads/2012/12/sprites.png
網頁即時通訊的網址試圖使之繼續工作。 http://www.priceofmilk.co.uk/uncategorized/ddd-2
可以使用CSS和HTML來實現,還是需要使用一些JavaScript? 任何幫助將不勝感激。
我舉了一個簡單的例子。 我使用背景色和錨點,但是您可以根據自己的情況輕松實現此目的。
更新了代碼,以便它使用您的圖像。
HTML
<a class="play_pause">PLAY</a>
CSS
.play_pause {
display: block;
width: 24px;
height: 23px;
text-indent: -99999px;
background: url(http://www.danceyrselfclean.com/wp-content/uploads/2012/12/sprites.png);
cursor: pointer;
}
.playing {
background-position: -27px 0;
}
.playing:hover {
background-position: -27px -28px !important;
}
.play_pause:hover {
background-position: 0 -28px;
}
和JS:
$(document).ready(function() {
$(".play_pause").click(function() {
$(this).toggleClass('playing');
});
});
那很簡單,您在哪里讀?
jQuery('.testclass .stratus').click(function{
jQuery(this).toggleClass('played');
})
CSS:
.played{
background-position: -1px -29px;
}
如果您只想檢測首次點擊,則可以在純CSS中通過給鏈接一個id並使用:target偽類(例如a#theid:target {...})來實現。
但是由於需要檢測第二次單擊,因此需要使用JS在CSS類之間進行切換。 基本方法是使用事件處理程序:
document.getElementById('theid').onclick = function(){
this.className = this.className=='play' ? 'pause' : 'play';
};
例如使用.querySelectorAll
和.addEventListener
,與當前的精靈 。 不使用jQuery。
var elm = document.querySelectorAll('.testclass .stratus'), i = elm.length, e;
while (e = elm[--i])
e.addEventListener('click', function () { // this fn generates the listener
var pause = false; // captured in scope, not global
return function () { // this is the actual listener
this.style.backgroundPositionX = (pause = !pause)?'-20px':'0px';
}
}(), false); // the () invokes the generator
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.