我无法通过使用JavaScript添加CSS opacity过渡。请告诉我代码有什么问题。 http://jsfiddle.net/copperspeed/bvWbB
(function () {
var myImgs = document.getElementById('vz0');
var i = 0;
function cycle() {
if (i <= 3) {
var myArray = [
'http://jsrun.it/assets/t/r/U/O/trUOT.jpg',
'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg',
'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg',
'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'
];
console.log(myArray[0]);
myImgs.setAttribute("src", myArray[i]);
if (myImgs.style.opacity === '0') {
console.log('trans');
myImgs.style.transitionProperty = 'opacity';
myImgs.style.transitionDuration = "1500ms";
}
if (myImgs.style.opacity === '1') {
console.log('opacity-0');
myImgs.style.opacity = '0';
}
i++;
setTimeout(function () {
cycle();
}, 3000);
答案 0 :(得分:0)
调试的第一条规则。如果IF语句中的某些内容没有发生,请查看条件。
您检查myImgs.style.opacity
是否等于0或1.使用console.log(myImgs.style.opacity);
,它会显示myImgs.style.opacity
等于空字符串。所以你的条件都没有发射过。
答案 1 :(得分:0)
您的脚本存在一些问题。
代码更改为1-3以上:
(function () {
var myImgs = document.getElementById('vz0');
var i = 0;
function cycle() {
if (i <= 3) {
var myArray = ['http://jsrun.it/assets/t/r/U/O/trUOT.jpg', 'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg', 'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg', 'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'];
myImgs.setAttribute("src", myArray[i]);
if (myImgs.style.opacity === '' || myImgs.style.opacity == 0) {
console.log(myImgs.style.opacity + '0');
myImgs.style.transitionProperty = 'opacity';
myImgs.style.transitionDuration = "1500ms";
myImgs.style.opacity = 1;
} else if (myImgs.style.opacity == 1) {
console.log(myImgs.style.opacity + '2');
myImgs.style.opacity = 0;
}
i++;
setTimeout(function () {
cycle();
}, 3000);
if (i === 4) {
i = 0;
}
}
}
cycle();
}());
对于上面的第4项 - 这是一个重构版本,它使用两个img元素来帮助管理进出的过渡:
HTML:
<div class="imgWrapper">
<img src="http://jsrun.it/assets/t/r/U/O/trUOT.jpg" id="vz0" class="vzImage" alt="first" height="300" width="300" />
<img src="http://jsrun.it/assets/t/r/U/O/trUOT.jpg" id="vz1" class="vzImage" alt="first" height="300" width="300" />
</div>
CSS:
.imgWrapper {
position: relative;
height: 300px;
width: 300px;
}
.vzImage {
opacity:0;
position: absolute;
top: 0; left: 0;
bottom: 0; right: 0;
}
脚本:
(function () {
var myImgs = document.getElementsByClassName('vzImage');
var myArray = ['http://jsrun.it/assets/t/r/U/O/trUOT.jpg',
'http://jsrun.it/assets/6/c/Y/s/6cYsH.jpg',
'http://jsrun.it/assets/w/M/r/i/wMriQ.jpg',
'http://jsrun.it/assets/5/Q/8/f/5Q8fW.jpg'];
// Consider moving this to .vsImage in stylesheet
for(var j = 0; j < myImgs.length; ++j) {
myImgs[j].style.transitionProperty = 'opacity';
myImgs[j].style.transitionDuration = "1500ms";
}
function cycle(i) {
var myArrayIdx = i % myArray.length;
var imgIdx = i % myImgs.length;
var prevImgIdx = (i-1) % myImgs.length;
myImgs[imgIdx].setAttribute("src", myArray[myArrayIdx]);
myImgs[imgIdx].style.opacity = 1;
if(myImgs[prevImgIdx]) {
myImgs[prevImgIdx].style.opacity = 0;
}
setTimeout(function () {
cycle(i+1);
}, 3000);
}
cycle(0);
}());