如何在徘徊时以固定的时间间隔对图像进行随机播放

时间:2016-08-06 19:53:46

标签: javascript jquery image onhover

研究后:
Changing images on hover 是最接近找到帮助我的东西。它没有多大帮助。我没有任何正式的网络体验。所以,任何人这样做,我都会无法理解a)修复我的问题,但b)实际上知道为什么这个东西不会改变图像..

所以这就是我在HTML中的地方:

<div class="navBar" id="myNavBar">    
    <ul id="navOptions">

        <li> <img id="logo" 
              src="images/logo.png" 
              onmouseover="hoverFunction(this);" ></li>

        <li class="active"><a href="default.asp">Home</a></li>
        <li><a href="news.asp">News</a></li>
        <li><a href="contact.asp">Contact</a></li>
        <li><a href="about.asp">About</a></li>
    </ul>
</div>

我的JavaScript:

function hoverFunction(element) {
    var images = ["images/logo.png",
                  "images/logo_2.png",
                  "images/logo_3.png",
                  "images/logo_4.png",
                  "images/logo.png"];

    for(var i=0; i < images.length; i++){
        $(element).attr("src",images[i]);
    }
    //element.setAttribute('src', 'images/logo_2.png');
}

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您想要的是,<img>悬停时,会定期更改图像。通常,这将通过在您收到setInterval()事件时使用mouseenter启动间隔计时器来完成。每次间隔触发时将调用的函数更改为下一个图像。当您收到mouseout事件时,您将使用clearInterval()停止间隔计时器。

当鼠标悬停在<div>上时,以下代码将循环显示图像:

var images = ["http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a",
              "http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/se/se-icon.png?v=93426798a1d4",
              "http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/sf/sf-icon.png?v=6c3100d858bb",
              "http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/su/su-icon.png?v=0ad5b7a83e49"
];
var curImageIndex = 0; // 0 is displayed by default
var intervalId; //Remember the ID of the interval so we can stop it later.

function startImageCycle(el){
    cycleImage(el); //Cycle the image now so feels responsive. Remove if not wanted.
    intervalId = setInterval(cycleImage,1000,el); //Change image every 1000ms (1s)
}
function stopImageCycle(el){
    clearInterval(intervalId);
}
function cycleImage(element){
    curImageIndex++;
    if(curImageIndex >= images.length) {
        curImageIndex = 0;
    }
    $(element).attr("src", images[curImageIndex]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navBar" id="myNavBar">
      <ul id="navOptions">
        <li>
          <img id="logo" src="http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a"
               onmouseenter="startImageCycle(this);" onmouseout="stopImageCycle(this);"
        </li>
        <li class="active"><a href="default.asp">Home</a>
        </li>
        <li><a href="news.asp">News</a>
        </li>
        <li><a href="contact.asp">Contact</a>
        </li>
        <li><a href="about.asp">About</a>
        </li>
      </ul>
    </div>

答案 1 :(得分:1)

要达到预期效果,请使用计数器

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Indeed Job search result</title>
    <script src="//code.jquery.com/jquery-2.1.4.js" type="text/javascript"></script>

    <style type="text/css">
       .pagination li{
            background-color: #000;
            padding: 5px;
            float:left;
            margin-right: 2px;
            border-radius: 5px;
            color: #FFF;
            cursor: pointer;
        }
    </style>
</head>
<body>
<script>

jQuery(function() {

    var resultLinks = $('body').find('#pagination');

    var location, country, city, region, limit = 10;
    $.get("//ip-api.com/json/", function (response) {
        console.log(response);
        city = (isNull(response.city))?(response.city+","):"";
        region = (isNull(response.region))?(response.region):"";
        location = city + region;
        country = response.country;
        console.log(country);
    }, "jsonp");

    $( "#searchResult" ).click(function() {
        jobSearch($('#location').val(),$('#jobname').val(),country,0,limit);
    });

    resultLinks.on('click', 'li', function (e) {
        var start = ($(this).text() - 1) * limit, end = start + limit;
        jobSearch($('#location').val(),$('#jobname').val(),country,start,end);
    });

    function isNull(value){
        if(typeof(value) === "object" || typeof(value) === "undefined" || value === "null" || value === "")
            return false;
        else
            return true;
    };
    function extractDomain(url) {
        var domain;
        //find & remove protocol (http, ftp, etc.) and get domain
        if (url.indexOf("://") > -1) {
            domain = url.split('/')[2];
        }
        else {
            domain = url.split('/')[0];
        }

        //find & remove port number
        domain = domain.split(':')[0];

        return domain;
    };
    function jobSearch(location,data,country,start,end){
        var serachData  =data;
        $.ajax({
            cache: false,
            data: $.extend({
                publisher: '7778623931867371',
                v: '2',
                format: 'json',
                q: data,
                l: location,
                radius: 50,
                limit:limit,
                sort: 'date',
                highlight: 1,
                filter: 1,
                latlong: 1,
                co: country.toLowerCase(),
                userip: '',
                useragent: ''
            }, { start: start, end: end }),
            dataType: 'jsonp',
            type: 'GET',
            timeout: 5000,
            url: '//api.indeed.com/ads/apisearch'
        })
        .done(function( data ) {
            var result="",pagination = "",i=2,style,url, paginationLimit = Math.ceil((data.totalResults)/limit);

            $.each( data.results, function( i, item ) {
                style = ((i%2) == 0)?"articaljoblistinggray":"articaljoblistingwhite"
                result = result + '<a target="_blank" href="'+item.url+'"><li class="articaljoblisting '+style+'" style="margin-bottom:3px;">'+item.jobtitle+'<br /><span style="color:black;">'+item.source+' - '+item.formattedLocation+'</span></li></a>';
                i++;
                url = item.url;
            });

            for (i = 1; i <= paginationLimit; i++) {
                pagination = pagination + '<li>'+i+'</li>';
            }

            $('#jobs-data').html('<ul style="list-style: none;margin: 0;padding:0;">'+result+'</ul><a style="float: right;" target="_blank" href="http://'+extractDomain(url)+'/jobs?q='+serachData+'&l='+location+'">Find more jobs</a>');
            $('#pagination').html('<ul class="pagination" style="list-style: none;margin: 0;padding:0;">'+pagination+'</ul>');
        });
    };
});

</script>
</body>
</html>

http://codepen.io/nagasai/pen/jAZogO

option2:更新的codepen

http://codepen.io/nagasai/pen/WxYwvK