2 回答
TA貢獻1155條經驗 獲得超0個贊
幾個機會:
將要素定義為列表
使用 動態填充要素值列表
new Array(3).fill().map()在圖像的包含元素上添加偵聽器,而不是圖像本身
使用數據屬性(例如
data-index)
const features = [
{
element: document.querySelector('.eyes'),
values: new Array(3).fill().map((value, index) => `http://guildofone.com/makeneki-neko/img/SVG/eyes${index}.svg`),
},
{
element: document.querySelector('.noses'),
values: new Array(3).fill().map((value, index) => `http://guildofone.com/makeneki-neko/img/SVG/nose${index}.svg`),
}
];
function initialize() {
features.forEach(feature => {
feature.element.addEventListener('click', () => {
const current = parseInt(feature.element.getAttribute('data-index'), 10);
const nextIndex = (current + 1) % feature.values.length;
feature.element.setAttribute('data-index', nextIndex);
updateFeature(feature);
});
updateFeature(feature);
});
}
function updateFeature(feature) {
const index = feature.element.getAttribute('data-index');
const img = feature.element.querySelector('img');
img.src = feature.values[index];
}
initialize();
<div class="eyes" data-index="0">
<img />
</div>
<div class="noses" data-index="0">
<img />
</div>
TA貢獻1795條經驗 獲得超7個贊
只需將所有類似的邏輯組合到一個函數中,不同的部分作為參數傳遞即可。在我的示例中,我也傳入了用于綁定事件的圖像和元素 - 函數中的其余實現是相同的。
window.onload = function() {
//eyes
var img_eyes = []
img_eyes[0] = "http://guildofone.com/makeneki-neko/img/SVG/eyes0.svg";
img_eyes[1] = "http://guildofone.com/makeneki-neko/img/SVG/eyes1.svg";
img_eyes[2] = "http://guildofone.com/makeneki-neko/img/SVG/eyes2.svg";
//face
var img_face = []
img_face[0] = "http://guildofone.com/makeneki-neko/img/SVG/face0.svg";
img_face[1] = "http://guildofone.com/makeneki-neko/img/SVG/face1.svg";
img_face[2] = "http://guildofone.com/makeneki-neko/img/SVG/face2.svg";
//build the rest of the images
//add the features
addFeature( document.querySelectorAll( "[name=eyes]" ), img_eyes )
addFeature( document.querySelectorAll( "[name=face]" ), img_face )
}
function addFeature( features, imgs ) {
//add the feature
for( var i=0; i < features.length; i++ ) {
var feature = features[i];
feature.addEventListener( "click", featureClicked(), false )
}
function featureClicked() {
let counter = 0;
return function( event ) {
counter++;
this.src = imgs[counter % imgs.length];
}
}
}
添加回答
舉報
