简体   繁体   English

如何在加载的页面上动态更改图像,并在每个图像上附加一个链接

[英]How to dynamically change images on a loaded page with a link attached to each images

I see this on most website.whereby once the page is loaded, they have a kinda image advert whereby it changes, maybe it has a set timer or something. 我在大多数网站上都看到了这一点。一旦页面被加载,他们就会有一个类似的图像广告,它会随之改变,也许它有一个设置好的计时器或其他东西。 And if you hover the cursor around the images, there's always a different link attached to it, that leads you to the page where it has been instructed to.How can i achieve similar thing. 而且,如果将光标悬停在图像周围,则始终会附有其他链接,该链接会将您带到已指示的页面。我该如何实现类似的目的。 Am thinking Php or maybe javascript, but would prefer php. 我在想PHP或Javascript,但更喜欢php。

You can use some javascript. 您可以使用一些JavaScript。

Let's say, you have this markup: 假设您有以下标记:

<a id='ad_link' href="http://url1.com">
    <img src='img1_url' />
</a>

And you receive this data from somewhere (for example, from your server via AJAX). 然后,您从某处(例如,通过AJAX从服务器)接收到此数据。

{"link": "url2.com", "img": "img2_url"}

Then you update your ad with this (using jQuery): 然后,您使用此代码(使用jQuery)更新广告:

function updateAd(ad_data) {
  $('#ad_link').attr('href', ad_data['link']);
  $('#ad_link img').attr('src', ad_data('img'));
}

Now, you can request new information in a various ways. 现在,您可以通过多种方式请求新信息。 setTimeout() or setInterval() are easy and probably the most obvious ways. setTimeout()setInterval()很简单,可能是最明显的方法。

php is server side language not client side, so if you already have images in browser php can't do anything with it, you can just use javascript (client side) to call to server for images, or another alternative to AJAX is that you will render all images you want to switch between but displayed will be just one and with javascript you will hide that image after some time and reveal another. php是服务器端语言,而不是客户端,因此,如果浏览器中已经有图像php不能执行任何操作,则可以使用javascript(客户端)调用服务器获取图像,或者AJAX的另一种替代方法是将呈现您要在其间切换但显示的所有图像,而只是一个图像,而使用javascript,您将在一段时间后隐藏该图像并显示另一个图像。

html:

<img id="first" src="first.jpg"/> 
<img id="second" src="second.jpg" style="display:none"/>; 

javascript:

setTimeout('change',3000);
function change() {

    $('first').hide();
    $('second').show();

}

something like this but better 这样的东西,但更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM