CSS代碼:
<style type="text/css">
*{
margin: 0;
padding: 0;
position: relative;
}
#div1{
display: flex;
align-items: flex-end;
justify-content: center;
width: 940px;
height: 430px;
margin: auto;
background-color: lightblue;
background: url("img/1.jpg");
}
#ul1{
list-style: none;
font-size: 40px;
color: red;
display: flex;
width: 100px;
height: 50px;
justify-content: space-around;
}
#ul1 li{
cursor: pointer;
}
</style>
html代碼如下:
<div id="div1">
<div id="div2">
<ul id="ul1">
<li id="list1">■</li>
<li id="list2">■</li>
<li id="list3">■</li>
<li id="list4">■</li>
</ul>
</div>
</div>
JS代碼如下:
<script type="text/javascript">
var index=0;
var listId=["list1","list2","list3","list4"];
var image=["url(img/1.jpg)","url(img/2.jpg)","url(img/3.jpg)","url(img/4.jpg)"];
var div=document.querySelector("#div1");
div.addEventListener('mouseover',stopShow);
div.addEventListener('mouseout',startShow);
var timeId;
var temp;
startShow();
function startShow(){
timeId=window.setInterval(function(){
index %= image.length;
document.querySelector("#div1").style.backgroundImage=image[index];
changeListStyle(index);
index+=1;
},2000);
}
function stopShow(){
window.clearInterval(timeId);
}
function changeListStyle(index){
var listStyle=document.querySelector("#"+listId[index]);
listStyle.style.color="greenyellow";
temp=["list1","list2","list3","list4"];
temp.splice(index,1);
console.log(temp);
for(i=0 ;i<temp.length;i+=1){
var listStyleOther=document.querySelector("#"+temp[i]);
listStyleOther.style.color="red";
}
}
var listLi=document.querySelectorAll("li");
for (i=0;i<listLi.length;i+=1){
listLi[i].addEventListener("mouseover",function(evt){
var singlelist=evt.target||evt.srcElement;
index=listId.indexOf(singlelist.id);
document.querySelector("#div1").style.backgroundImage=image[index];
changeListStyle(index);
})
}
</script>
效果:
QQ截圖20181106203114.png
QQ截圖20181106203125.png
說明
1、整體采用flex的方式進行CSS布局,彈性盒子模型靈活多變,易于得到理想的布局;
2、index是整體程序的關鍵,控制index就控制了div背景圖和li標簽內容的顯示狀態;
3、抽離出changeListStyle函數作為控制Li標簽內容color變化的函數,其中temp是用于將非index選中的Li標簽內容變為統一的顏色;temp在循環不斷的被改變,應該有垃圾回收機制將未引用的對象清理;