[英]Switching style between two elements on photo gallery change
因此,我的首頁上有一個圖庫,可以在兩個圖像之間切換; 每個圖像都鏈接到不同的頁面。 現在,在那個畫廊旁邊,我有兩個鏈接都指向相同的兩個頁面。 這個想法是,當顯示圖像A時,應以邊框突出顯示側鏈接A。 我一直遇到的問題是,一旦任一側鏈突出顯示,我就真的不知道該如何突出顯示它。 它們不會切換圖像,而是保持突出顯示狀態。
var debugLink = "#firstLink"; function displayNextImage() { index++; if(index >= indexgalpics.length) { index=0; } //---this is where I set the var debugLink which is // supposed to carry the selected linke if(index == 0) { console.log("first link selected"); //---when image A is showing, top side-link should be highlighted //---ok so we know this much works, it seems these double equal // signs are very important here. //---makeActive(); //---but once makeActive() is called here, it makes the first link // active for the entire time. //---we can't put the entire style code here because same as before, // it just keeps the link highlighted forever debugLink = "#firstLink"; //---ok so i can set a var at top to a value in the makeActive() function, // but i think the way JS works highlights either one forever debugLink = "#firstLink"; } else if(index == 1) { console.log("second link should be selected"); //---when image B is showing, bottom side-link should be highlighted debugLink = "#secondLink"; } showImg(); } function makeActive() { var activeLink = document.querySelector(debugLink); //---adds style to the debugLink }
在showImg()函數中調用makeActive()函數,在另一個設置計時器的函數中調用displayNextImage()函數。
我通過為索引使用布爾值來稍微改變了您的方法,因為您似乎只需要兩個狀態。
這是修訂版:
注意:在此代碼中,我使用了定制函數使代碼更易於閱讀。 我創建了
hasClass(el,class)
,addClass(el,class)
,removeClass(el,class)
,toggleClass(el,class,bool)
。 您可以在最終的JS小提琴中找到它們。
// Register the link elements
var links = {
true : document.getElementById('firstLink'),
false : document.getElementById('secondLink')
},
// Keep track of selected link (replaces your 'index')
leftLinkActive = false,
// Just so you don't go get it every time
gallery = document.getElementById('gallery');
// Let's trigger the gallery
displayNextImage();
// We'll change the active link and show the correct image
function displayNextImage(){
leftLinkActive = !leftLinkActive;
if(leftLinkActive){ console.log("first link selected"); }
else{ console.log("second link selected"); }
makeActive();
showImg();
// Let's do that again in 2 seconds
setTimeout(displayNextImage,2000);
}
// Add / remove the active class
function makeActive(){
addClass( links[ leftLinkActive ], 'active-class');
removeClass( links[ !leftLinkActive ], 'active-class');
}
// Change the image with a small fadeOut transition
function showImg(){
addClass(gallery,'fadeOut');
setTimeout(function(){
// Here we switch from img1 and img2
gallery.style.backgroundImage = 'url('+(leftLinkActive?'im1.jpg':'im2.jpg')+')';
removeClass(gallery,'fadeOut');
},200);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.