0
我正在使用react和redux,並且我正在嘗試創建一個reducer。基本上,我有一個div列表。當我點擊div時,我想更新它的z-index,以便它是更高的索引,保持z-index層次結構。如何創建一個reducer來處理z-index堆棧
見琴: https://jsfiddle.net/pablodarde/mvv6chz3/
的changeStack
功能就像是我的減速器。
在這裏,我只是想更新notes
數組由更高的索引(最後一個元素,更高的索引)排序。
在此先感謝
HTML
<div id="container">
</div>
的JavaScript
let notes = [
{
id: 'one',
label: 'One',
},
{
id: 'two',
label: 'Two',
},
{
id: 'three',
label: 'Three',
},
{
id: 'four',
label: 'Four',
},
];
const list = document.querySelector('#container');
notes.map((item) => {
const elem = document.createElement('div');
elem.id = item.id;
elem.innerHTML = item.label;
list.appendChild(elem);
});
const btn1 = document.querySelector('#one');
const btn2 = document.querySelector('#two');
const btn3 = document.querySelector('#three');
const btn4 = document.querySelector('#four');
btn1.addEventListener('click', function(e) {
changeStack(e.target.id);
});
btn2.addEventListener('click', function(e) {
changeStack(e.target.id);
});
btn3.addEventListener('click', function(e) {
changeStack(e.target.id);
});
btn4.addEventListener('click', function(e) {
changeStack(e.target.id);
});
function changeStack(id) {
let index = notes.length - 1;
notes = notes.map((item, idx) => {
if (idx === notes.length - 1) {
console.log('last: ', idx);
return notes[index];
} else if (item.id == id) {
console.log('item.id == id: ', idx);
index = idx;
return notes[idx + 1];
} else if (item.id > id) {
console.log('item.id > id: ', idx);
return item;
} else {
console.log('else: ', idx);
return item;
}
});
console.log(notes);
}
CSS
body, html {
width: 100%;
height: 100%;
}
#container {
position: relative;
width: 100%;
height: 100%;
background: #ddd;
}
#one, #two, #three, #four {
position: absolute;
width: 120px;
height: 120px;
background: #990;
box-shadow: 2px 2px 2px rgba(0,0,0,.4);
border: 1px solid rgba(0,0,0,.4);
}
#one {
top: 0;
left: 0;
z-index: 10;
}
#two {
top: 40px;
left: 40px;
z-index: 20;
}
#three {
top: 80px;
left: 80px;
z-index: 30;
}
#four {
top: 120px;
left: 120px;
z-index: 40;
}