简体   繁体   English

我怎样才能使这个活动的onclick?

[英]How could I make this active onclick?

var span = document.getElementById('loading_dots');

var int = setInterval(function() {
    if ((span.innerHTML += '●').length == 4) 
        span.innerHTML = '';
}, 400);

(function(){
    var loading_dots = document.getElementById("loading_dots"),

      show = function(){
        loading_dots.style.display = "block";
        setTimeout(hide, 5000); // 5 seconds
      },

      hide = function(){
        loading_dots.style.display = "none";
      };

    show();
})();

How can I make it so loading_dots start on the click of a button, and re-activates everytime I click the button? 如何使loading_dots从单击按钮开始,并在每次单击按钮时重新激活? the bottom function is to stop it after 5 seconds, maybe could merge it into one function? 最底层的功能是在5秒钟后将其停止,也许可以将其合并为一个功能?

Needs to work for 3 seperate buttons and relaunch on click of each, also needs to display inside of <span class="loading_dots" id="loading_dots"></span> any method is fine, css, jquery, or javascript 需要使用3个单独的按钮并在每次单击时重新启动,还需要显示在<span class="loading_dots" id="loading_dots"></span>任何方法都可以,例如css,jquery或javascript

here is a jQuery version: 这是一个jQuery版本:

 (function ( $ ) { $.fn.loader = function( options ) { var settings = $.extend({ text:"●", spn: undefined }, options ); $.each(this, function(){ var btn = this; var int; var spn; if (settings.spn === undefined) { spn = $("<span/>" , { "class":"loading_dots" }); $(btn).append(spn); } else { spn= $(settings.spn); } var show = function(){ btn.setAttribute("disabled", "disabled") clearInterval(int); spn.show(); int = setInterval(function() { if ((spn[0].innerHTML += settings.text).length == 4) spn.html(""); }, 400); setTimeout(hide, 5000); // 5 seconds } var hide = function (){ spn.hide(); btn.removeAttribute("disabled", "disabled") clearInterval(int); } btn.addEventListener("click", show); }); }; }( jQuery )); // now bind it by its class, this only need to be run once every time new button is added to the html $(".btn").loader({spn:".loading_dots"}); // and you could also specify the text by // $(".btn").loader({text: "*"}); 
 .loading_dots { color:red; display:none; width:100%; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <span class="loading_dots"></span> <button class="btn" type="button" > submit </button> <button class="btn" type="button" > submit </button> </div> 

If you want to add an event listener for a button click, just select the buttons, and add the listeners in a loop: 如果要为单击按钮添加事件侦听器,只需选择按钮,然后在循环中添加侦听器:

document.querySelectorAll("button").forEach(e => e.addEventListener("click", myFunc));

Alternatively, listen for any click, then check if the event's target is a button: 或者,侦听任何单击,然后检查事件的目标是否为按钮:

document.addEventListener("click", (e) => if (e.target.tagName == "BUTTON") myFunc());

You could use CSS for the most part of your code, and than simply toggle a show class on the parent #loading element: 您可以在大部分代码中使用CSS,而不仅仅是在父#loading元素上切换show类:

 const Loading = () => { let tOut = null; const el = document.querySelector("#loading"); const show = () => { el.classList.add('show'); tOut = setTimeout(hide, 5000); }; const hide = () => { el.classList.remove('show'); clearTimeout(tOut); }; return { show, hide }; }; const loadingDots = Loading(); const loadBtns = document.querySelectorAll('.load'); [...loadBtns].forEach(el => el.addEventListener('click', loadingDots.show)); // you can always use loadingDots.hide() to hide when needed (before the 5sec ticks out) 
 #loading { position: fixed; z-index: 100; top:0; left: 0; width:100vw; height:100vh; display:flex; background: rgba(0,0,0,0.5); color: #fff; font-size: 3em; align-items: center; justify-content:center; visibility: hidden; opacity: 0; transition: 0.4s; } #loading.show { opacity: 1; visibility: visible; } @keyframes blink { 50% {opacity: 1;} } #loading i:after {content: "\\25cf";} #loading i { opacity: 0; animation: blink 1.2s infinite; } #loading i:nth-child(2) { animation-delay: .2s; } #loading i:nth-child(3) { animation-delay: .4s; } 
 <div id="loading"><i></i><i></i><i></i></div> <button class="load">LOAD</button> <button class="load">LOAD</button> <button class="load">LOAD</button> 

A plain javascript version with the option to programmatically/manually stop displaying the loading dots. 一个普通的javascript版本,可以选择以编程方式/手动方式停止显示加载点。 Just pass the id of the parent element you want the loading to be attached to. 只需传递您要附加加载的父元素的ID。 By default the loading will be appended to the parent but you can optionally pass an object as the last parameter with a position property. 默认情况下,加载将添加到父对象,但是您可以选择将对象作为带有position属性的最后一个参数传递。

 function removeLoading(id) { var parent = document.getElementById(id); var spans = parent.getElementsByClassName("loading_dots"); while (spans.length > 0) { var span = spans[0]; if (span.dataset.timerId) { clearTimeout(span.dataset.timerId); } span.remove(); } } function addLoading(id, options) { options = options || {}; var parent = document.getElementById(id); var existingSpans = parent.getElementsByClassName("loading_dots"); if (existingSpans.length > 0) { removeLoading(id); } var span = document.createElement("span"); span.setAttribute("class", "loading_dots"); if (options.timerId) { span.dataset.timerId = options.timerId; } parent.insertAdjacentElement(options.position || "beforeend", span); setInterval(function () { if ((span.innerHTML += '●').length == 4) span.innerHTML = ''; }, 400) } function addLoadingWithTimeout(id, ms, options) { options = options || {}; var timerId = setTimeout(function () { removeLoading(id) }, ms); options.timerId = timerId; addLoading(id, options); } 
 <p id="load1">Load 1 - Will stop automatically in 3 seconds after starting. </p> <button onclick="addLoadingWithTimeout('load1', 3000)">Start Load 1</button> <button onclick="removeLoading('load1')">Stop Load 1</button> <p id="load2">Load 2 - Only manual Stop </p> <button onclick="addLoading('load2')">Start Load 2</button> <button onclick="removeLoading('load2')">Stop Load 2</button> 

Here you go. 干得好。 on the HTML side, you just pass the event to the button that you want and then the id, as a string, of the span/div where you want the load icons to appear. 在HTML端,您只需将事件传递到所需的按钮,然后将其作为要显示加载图标的span / div的ID(作为字符串)传递给它。

HTML: HTML:

  <button id="btn" onclick="load(event, 'loadDiv')">Load</button>
  <div>
    <span id="loadDiv"></span>    
  </div>

Below, we are getting the btn id from event so you don't have to manually pass it everytime. 在下面,我们从事件获取btn id,因此您不必每次都手动传递它。 Then we are defining function for the innerhtml icons. 然后,我们为innerhtml图标定义函数。 Lastly, we are running the showIcon function every .4s and then clearing the interval after 5 seconds. 最后,我们每0.4秒运行一次showIcon函数,然后在5秒后清除间隔。

JS: JS:

function load(e, location) {
  var btn = document.getElementById(e.srcElement.id)
  var loadDiv = document.getElementById(location)

  function showLoad() {
    if (loadDiv.innerHTML.length < 3) {
      return loadDiv.innerHTML += '●'
    }
    loadDiv.innerHTML = ''
  }

  (function() {
    var loadIcons = setInterval(function() {
      showLoad()
    }, 400)

    var clear = setTimeout(function() {
      clearInterval(loadIcons)
    }, 5000)
  })()
}

Hope this helps! 希望这可以帮助!

You can define your code in a function and add click handler to the button. 您可以在函数中定义代码,并将点击处理程序添加到按钮。

function myFunc() {
 var span = document.getElementById('loading_dots');

 var int = setInterval(function() {
     if ((span.innerHTML += '●').length == 4) 
         span.innerHTML = '';
 }, 400);

 (function(){
     var loading_dots = document.getElementById("loading_dots"),

       show = function(){
         loading_dots.style.display = "block";
         setTimeout(hide, 5000); // 5 seconds
       },

       hide = function(){
         loading_dots.style.display = "none";
       };

     show();
 })();
}

document.getElementById("myBtn1").addEventListener("click", myFunc); 
document.getElementById("myBtn2").addEventListener("click", myFunc); 

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

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