简体   繁体   中英

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.

You can use some 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).

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

Then you update your ad with this (using 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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