一段时间后如何更改img src?

时间:2018-04-16 23:30:42

标签: javascript jquery dom

P= [0 1 1 1 0 0 0 1 1 1 1 0 1 1 0 0 1 0 0 1 0 0 1 1 0 1 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1]; L=1; % a submatrix has to containg at least L ones and L zeros H=5; % max area of a submatrix submats = []; for sH = H:-1:2*L div_sH=divisors(sH); % find all divisors of sH for i = 1:length(div_sH) % cycle over all couples of divisors %number of rows of the current submatrix nrows=div_sH(i); % number of columns of the current submatrix ncols=div_sH(end-i+1); % perpare matrix to convolve P with m = zeros(nrows*2-1,ncols*2-1); m(1:nrows,1:ncols) = 1; % get the number of ones in the top left corner each submatrix submatsums = conv2(P,m,'same'); % set values where the submatrices go outside P invalid validsums = zeros(size(P))-1; validsums(1:(end-nrows+1),1:(end-ncols+1)) = submatsums(1:(end-nrows+1),1:(end-ncols+1)); % get the indexes where the number of ones and zeros is >= L topLeftIdx = find(validsums >= L & validsums<=sH-L); % save submatrixes in following format: [index, nrows, ncols] % You can ofc use something different, but it seemed the simplest way to me submats = [submats ; [topLeftIdx bsxfun(@times,[nrows ncols],ones(length(topLeftIdx),1))]]; end end 元素具有某个img。我想在让1000分之后更改src然后在1000毫秒后更改另一个,然后在最后一张图像处停止。这可能在jQuery中,src可能吗?

2 个答案:

答案 0 :(得分:4)

将图像路径放在一个数组中。然后,使用计时器(setInterval()setTimeout()),您可以使用数组中的下一个项目更改图像的来源,直到结束。

使用vanilla JavaScript可以做的任何事情都可以用JQuery来完成,但是JQuery过度使用了,对于这么简单的事情来说,这样做会有点过分。

&#13;
&#13;
var paths =
[ "https://www.spreadshirt.com/image-server/v1/mp/designs/12386804,width=178,height=178/winking-smiley-face.png",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTUirw89Ct-tBfgNgrCV8ygX65aomMvVbr1LsEgnaH8eJBG3FZH",
"https://www.energylivenews.com/wp-content/uploads/2014/06/Smiley-face-emoticon-575.jpg"];

var img = document.getElementById("img");
var i = 0;
var timer = setInterval(function(){
  // If we've reached the end of the array...
  if(i >= paths.length){
   clearInterval(timer);     // Stop the timer
   return;                   // Exit the function
  }
  img.src = paths[i++]; // Sete the path to the current counter and then increase the counter
}, 1000);
&#13;
img {
  width:200px;
}
&#13;
<img id="img">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于无限循环,将上面的代码更改为:

var img = document.getElementById("img");
var i = 0;
var timer = setInterval(function(){
// If we've reached the end of the array...
if(i >= paths.length){
i=0;
}
img.src = paths[i++]; // Sete the path to the current counter and then increase the counter
}, 1000);