
[spoiler]
Кроссбраузерный код для отмены действия по умолчанию:
element.onclick = function(event) { event = event || window.event; if (event.preventDefault) { // если метод существует event.preventDefault(); // то вызвать его } else { // иначе вариант IE8-: event.returnValue = false; } } // e.preventDefault() — не даст сработать событию по-умолчанию. Например, если это применить к ссылке, то переход по ссылке не будет работать. // e.stopPropagation() — Отменяет событие, наследуемое текущим элементом от родительского элемента. Т.е. событие родителя остается активным на родителе, но не распространяется на наш элемент. |
Как узнать на экране элемент или нет?
var elem = document.getElementById('pk_element'); $("body").on('click', function(){ if ($(document).scrollTop() + $(window).height() > $(elem).offset().top && $(document).scrollTop() - $(elem).offset().top < $(elem).height()) console.log('элемент на экране'); else console.log('элемент не на экране'); }); [SIZE=5]Как двигать фон при скроллинге?[/SIZE] Это часто встречается на лэндингах - прокручиваешь страницу, а фон движется быстрее или медленнее скроллинга. [CODE]window.onload = function() { var height = window.innerHeight; //Высота экрана пользователя var scrollHeight = document.documentElement.scrollHeight; var clientHeight = document.documentElement.clientHeight; var scrollHeight = Math.max(scrollHeight, clientHeight); //Высота всей страницы var bg = document.getElementById('bg'); var bgHeight = bg.height; //Высота изображения window.onscroll = function() { var a = window.pageYOffset || document.documentElement.scrollTop;; //Получаем при каждой прокуртке позицию скроллинга bg.style.top = -(bgHeight - height)*(a/(scrollHeight-height)) +"px" } window.onresize = function() { height = window.innerHeight; //Высота экрана пользователя scrollHeight = document.documentElement.scrollHeight; clientHeight = document.documentElement.clientHeight; scrollHeight = Math.max(scrollHeight, clientHeight); //Высота всей страницы bgHeight = bg.height; //Высота изображения window.onscroll() } } |
Как обойтись без jQuery
Что делать когда нужна сущая мелочь, но ради нее приходится загружать всю библиотеку jQuery/
ready function ready(fn) { if (document.readyState != 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } hide el.style.display = 'none'; show el.style.display = ''; addclass if (el.classList) el.classList.add(className); else el.className += ' ' + className; after el.insertAdjacentHTML('afterend', htmlString); each var elements = document.querySelectorAll(selector); Array.prototype.forEach.call(elements, function(el, i){}); find document.querySelectorAll('.my #awesome selector'); html el.innerHTML text el.textContent next el.nextElementSibling ajax post var request = new XMLHttpRequest(); request.open('POST', '/my/url', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.send(data); ajax getjson var request = new XMLHttpRequest(); request.open('GET', '/my/url', true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! var data = JSON.parse(request.responseText); } else { // We reached our target server, but it returned an error } }; request.onerror = function() { // There was a connection error of some sort }; request.send(); |