簡體   English   中英

隨機旋轉范圍的內容

[英]Randomly rotate content of a span

我正在嘗試將文本的<span>更改為七個文本塊之一。 我找到了可以使用以下Javascript來幫助我完成操作的教程,但是,它依賴於保存在<ul> 我認為我無法做到這一點,因為我需要將更改后的文本顯示在預先存在的段落中。

我在想可能有一種方法可以給span提供一個id,然后在Javascript中設置內容的不同選項。

我只希望更改在頁面加載或刷新時隨機發生,沒有讓它發生在用戶輸入或計時器上那樣復雜的事情。

以下是我在教程中找到的腳本,也許只是一個簡單修改的​​情況。 不過,我真是個新手,除非明確說明,否則我真的不知道從哪里開始。

<script type="text/javascript">

this.randomtip = function(){
    var length = $("#tips li").length;
    var ran = Math.floor(Math.random()*length) + 1;
    $("#tips li:nth-child(" + ran + ")").show();
};

$(document).ready(function(){   
    randomtip();
});

</script>

像這樣的作品:

Java腳本

<script type="text/javascript">
    $(document).ready( function() {

        // hide all of the tips
        $('#tips').children('.tip').hide();

        // randomly select one tip to show
        var length = $("#tips .tip").length;    
        // **EDIT **
        // This code was buggy!
        //var ran = Math.floor(Math.random()*length) + 1;
        //$("#tips .tip:nth-child(" + ran + ")").show();
        // Use this instead:
        var ran = Math.floor((Math.random()*length));
        $('#tips > .tip:eq('+ran+')').show();
    });
</script>

的HTML

<p id="tips">
    <strong>Random Tip: </strong>
    <span class="tip">This is tip 1.</span>
    <span class="tip">This is tip 2.</span>
    <span class="tip">This is tip 3.</span>
    <span class="tip">This is tip 4.</span>
    <span class="tip">This is tip 5.</span>
    <span class="tip">This is tip 6.</span>
    <span class="tip">This is tip 7.</span>
</p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM