簡體   English   中英

如何讓復選框開關來回改變英雄背景?

[英]How to make checkbox switch change hero background back and forth?

這些是當前的代碼片段。 我嘗試了幾種不同的方法,但似乎沒有任何效果。 請幫忙!!!

HTML 片段

 <div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
    <label class="onoffswitch-label" for="myonoffswitch">
       <span class="onoffswitch-inner"></span>
       <span class="onoffswitch-switch"></span>
    </label>
  </div>

JQuery 代碼段

var backgroundImg = ['../images/heroBG.jpg', '../images/heroBG2.jpg'
];
var backgroundCount = 0;

$(function () {
    $('hero').css('background', 'url(' + backgroundImg[backgroundCount] + ')');
});

$('myonoffswitch').on('click', function () {
    backgroundCount++;
    if (backgroundCount > backgroundImg.length - 1) backgroundCount = 0;
    $('hero').css('background', 'url(' + backgroundImg[backgroundCount] + ')');
});

在jQuery中通過ID引用元素,你需要使用#

$('myonoffswitch')將檢查任何html元素名稱myonoffswitch 要獲取 ID 為myonoffswitch的元素,您需要使用$('#myonoffswitch')

$('#myonoffswitch').on('click', function () {
    backgroundCount++;
    if (backgroundCount > backgroundImg.length - 1) backgroundCount = 0;
    //Assuming hero is ID of some element
    $('#hero').css('background', 'url(' + backgroundImg[backgroundCount] + ')');
});

您應該使用background-image而不是background ,因此您的代碼應如下所示:

$('#hero').css('background-image', 'url(' + backgroundImg[backgroundCount] + ')');

此外,在引用 ID 時您需要一個# ,因此$('myonoffswitch')應該是$('#myonoffswitch')並且$('hero')應該是$('#hero')

暫無
暫無

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

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