Как я могу сделать это активным onclick?

    // Change this to the day in the future
$day = 15;

// Change this to the month in the future
$month = 11;

// Change this to the year in the future
$year = 2012;

// $days is the number of days between now and the date in the future
$days = (int)((mktime (0,0,0,$month,$day,$year) - time(void))/86400);

echo "There are $days days until $day/$month/$year";
0
задан Jack Bashford 24 January 2019 в 12:21
поделиться

6 ответов

Простая версия JavaScript с возможностью программно / вручную прекратить отображение точек загрузки. Просто передайте идентификатор родительского элемента, к которому вы хотите привязать загрузку. По умолчанию загрузка будет добавлена ​​к родителю, но вы можете при желании передать объект в качестве последнего параметра со свойством 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>

0
ответ дан nireno 24 January 2019 в 12:21
поделиться

Вы можете использовать CSS для большей части своего кода, а затем просто переключить класс show на родительский элемент #loading:

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>

0
ответ дан Roko C. Buljan 24 January 2019 в 12:21
поделиться

Вот, пожалуйста. на стороне HTML вы просто передаете событие нужной кнопке, а затем в виде строки span / div, где должны отображаться значки загрузки.

HTML:

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

Ниже мы получаем btn id из события, поэтому вам не нужно вручную передавать его каждый раз. Затем мы определяем функцию для иконок innerhtml. Наконец, мы запускаем функцию showIcon каждые 4 секунды, а затем очищаем интервал через 5 секунд.

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)
  })()
}

Надеюсь, это поможет!

0
ответ дан Kendall Adkins 24 January 2019 в 12:21
поделиться

Если вы хотите добавить прослушиватель событий для нажатия кнопки, просто выберите кнопки и добавьте прослушиватели в цикле:

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

Кроме того, прослушайте любой щелчок, а затем проверьте, если событие цель - кнопка:

document.addEventListener("click", (e) => if (e.target.tagName == "BUTTON") myFunc());
0
ответ дан Jack Bashford 24 January 2019 в 12:21
поделиться

Вы можете определить свой код в функции и добавить обработчик щелчка к кнопке.

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); 
0
ответ дан user1579234 24 January 2019 в 12:21
поделиться

вот версия 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>

0
ответ дан marc_s 24 January 2019 в 12:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: