С Новым годом! Форум программистов, компьютерный форум, киберфорум
JavaScript для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 Аватар для Turbina_trista
2 / 2 / 0
Регистрация: 28.06.2017
Сообщений: 55

В чем суть кода?

10.02.2018, 12:55. Показов 1128. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый день

Скачал сайт, в нем есть некоторые JS, будьте добры, расскажите что они делают вкратце.
Jquery не скидываю, только 3 скрипта, один из них называется Плагины.

Первый скрипт:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
var detects = {
    paste: [],
    timer: 0,
    interval: null
};
function onPaste(e) {
    var tagName = e.target.tagName;
    var name = $(e.target).attr('name');
    detects.paste.push({
        name: name,
        tag: tagName
    });
}
 
function startTimer() {
    detects['interval'] = setInterval(function () {
        detects.timer++;
    }, 1000);
}
function stopTimer() {
    clearInterval(detects.interval);
}
 
startTimer();
$(function () {
    $(document.body).on('paste', onPaste);
    $('form').on('submit', function () {
        stopTimer();
        delete detects['interval'];
        var detectsString = JSON.stringify(detects);
        detectsString = detectsString.replace(/"/g,"'");
        $('<input type="hidden" name="detects" value="' + detectsString + '">').appendTo(this);
        startTimer();
        return true;
    });
});


Второй скрипт:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    $(document).ready(function () {
    $('.color-block ul>li').click(function () {
        $('body').find('input[name="color"]').val($(this).attr('value'));
        $('body').find('.color-block ul').children('li').removeClass('active');
        $('body').find('.info-block3 .content ul>li').children('div').removeClass('active');
        $('body').find('.info-block3 .preview>img').hide();
        $('body').find('.color-block ul>li.' + $(this).attr('class')).addClass('active');
        $('body').find('.info-block3 .content ul>li[value="' + $(this).attr('value') + '"]>div').addClass('active');
        $('body').find('.info-block3 .preview>img[data-idcolor="' + $(this).attr('value') + '"]').fadeIn();
        $(this).parent().children('li').removeClass('active');
        $(this).addClass('active');
    });
 
    $('.info-block3 .content ul>li>div').click(function () {
        $('body').find('input[name="color"]').val($(this).attr('value'));
        $('body').find('.info-block3 .content ul>li').children('div').removeClass('active');
        $(this).parents('.right-side').find('.preview>img').hide();
        $('body').find('.color-block ul').children('li').removeClass('active');
        $('body').find('.info-block3 .content ul>li.' + $(this).parent().attr('class') + '>div').addClass('active');
        $('body').find('.info-block3 .preview>img[data-idcolor="' + $(this).parent().attr('value') + '"]').fadeIn();
        $('body').find('.color-block ul>li[value="' + $(this).parent().attr('value') + '"]').addClass('active');
        $(this).parent().children('div').removeClass('active');
        $(this).addClass('active');
    });
    GetCount();
    window.isValidPhone = function (number) {
        if (number) {
            var phone = number.replace(/\D/g, '');
            if (phone && phone.length == 11) {
                return true;
            }
        }
        return false;
    };
});
//Timer
var today = new Date(),
    tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
tomorrow = new Date(tomorrow.getFullYear(), tomorrow.getMonth(), tomorrow.getDate(), 0, 0, 0);
function GetCount() {
    dateNow = new Date();
    amount = tomorrow.getTime() - dateNow.getTime();
    delete dateNow;
    if (amount < 0) {
        $('.countdown').html('<div><span>00</span><p>Часов</p></div><b>:</b><div><span>00</span><p>Минут</p></div><b>:</b><div><span>00</span><p>Секунд</p></div>');
    } else {
        hours = 0;
        mins = 0;
        secs = 0;
        amount = Math.floor(amount / 1000);
        amount = amount % 86400;
        hours = Math.floor(amount / 3600);
        amount = amount % 3600;
        mins = Math.floor(amount / 60);
        amount = amount % 60;
        secs = Math.floor(amount);
        if (hours < 10) hours = '0' + hours;
        if (mins < 10) mins = '0' + mins;
        if (secs < 10) secs = '0' + secs;
 
        $('.countdown').html('<div><span>' + hours + '</span><p>Часов</p></div><b>:</b><div><span>' + mins + '</span><p>Минут</p></div><b>:</b><div><span>' + secs + '</span><p>Секунд</p></div>');
        setTimeout("GetCount()", 1000);
    }
}
jQuery().ready(function () {
    $('a[href*=#]:not([href=#]):not(.fancybox):not(a[href="#close"])').click(function () {
 
        target = $(this).attr('href');
        console.log(target);
        $("html, body").animate({scrollTop: $(target).offset().top - 40}, 1000);
        return false;
 
    });
});

Файл Plugins:

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffleArray(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;
 
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
 
    return array;
}
var mainNow = 0;
 
function addTopLine(isMobile) {
    isMobile = isMobile ? isMobile : false;
    var allToday = new Date().getHours() * 100 + Math.floor(Math.random() * 1000);
    var now = mainNow != 0 ? mainNow : getRandomInt(45, 150);
    mainNow = now;
    var todayBuy = getRandomInt(50, 100) + new Date().getHours();
    if (allToday <= todayBuy) {
        todayBuy = Math.floor(allToday / 2) + 2;
    }
    var allHeight = isMobile ? 34 : 36;
    var html = '<style>.top-line span.mobile{height: 35px;padding-top: 10px;font-size: 12px !important;box-sizing: border-box;}' +
        'body{padding-top:34px !important;}' +
        '.top-line span{font-family: Arial !important;font-size:21px !important;}' +
        '.top-line .all-today.mobile{display:none;}' +
        '.tm-block-navbar{top: 36px !important;}' +
        '.all-today{background-image: url(http://static.best-gooods.ru/img/all.png);height: 28px;padding-left: 45px;background-repeat: no-repeat;background-position: 5px;margin-left: 10px;display: inline-block;padding-top: 8px;margin-top: 0;}' +
        '.now{background-image: url(http://static.best-gooods.ru/img/now.png);height: 28px;padding-left: 45px;background-repeat: no-repeat;background-position: 5px;margin-left: 10px;display: inline-block;padding-top: 8px;margin-top: 0;border-left: 3px solid #E4E4E4;}' +
        '.today-buy{background-image: url(http://static.best-gooods.ru/img/buy.png);height: 28px;padding-left: 45px;background-repeat: no-repeat;background-position: 5px;margin-left: 10px;display: inline-block;padding-top: 8px;margin-top: 0;border-left: 3px solid #E4E4E4;}' +
        '.top-line .now.mobile{border-left:0;}</style>' +
        '<div class="top-line" style="overflow: hidden;box-sizing: border-box; z-index: 99999;height:'+allHeight+'px; text-align:center;background: #F1EDEE; position: fixed; width:100%;top:0; left:0;">' +
        '<div style="font-size: 21px;color: #000;display:inline-block;">' +
        '<span class="all-today '+(isMobile ? 'mobile' : '')+'">Посетителей сегодня: <strong>' + allToday + '</strong></span>' +
        '<span class="now '+(isMobile ? 'mobile' : '')+'">Сейчас на сайте: <strong>' + now + '</strong></span>' +
        '<span class="today-buy '+(isMobile ? 'mobile' : '')+'">Покупок сегодня: <strong>' + todayBuy + '</strong></span>' +
        '</div></div>';
    $(html).appendTo($(document.body));
}
function showSwimmer() {
    var count = mainNow != 0 ? mainNow : getRandomInt(45, 150);
    var bottom = 6;
    if ($('.delivery-notify').length) {
        bottom = 88;
    }
    mainNow = count;
    var html = '<div class="swimmer" style="font-family: Arial; font-size: 12px;z-index:991001;position: fixed; bottom:' + bottom + 'px;color:black;line-height: normal; left: 6px; width:265px;height: 73px;background: #FFFFEA; border-radius: 5px; border:1px solid #000; padding: 10px;box-sizing: border-box;">' +
        '<div class="close-swimmer" style="cursor:pointer;width: 13px;height: 13px;font-size: 22px;line-height: 0.65;position: absolute;top: 10px;right:10px; background: white;color:#9C8B74;border: 1px solid #9C8B74; border-radius: 3px;">&times;</div>' +
        '<img src="swimmer.png"/*tpa=http://static.best-gooods.ru/img/swimmer.png*/ style="width:50px; height: 50px; float: left;padding-right: 10px;border:0;">' +
        'Сейчас  ' + count + ' пользователей просматривают эту страницу вместе с вами.' +
        '</div>';
    $(html).appendTo($(document.body));
    $('.close-swimmer').on('click', function () {
        $('.swimmer').remove();
    });
    setInterval(function () {
        if ($('.delivery-notify').length) {
            $('.swimmer').css('bottom', 88);
        } else {
            $('.swimmer').css('bottom', 6);
        }
    }, 1000);
}
function freezeMoney(balance, dollar) {
    var html = '<style>' +
        '.freezing-info-packages {font-size: 20px;color: #000000;padding-top: 12px;z-index: 2;position: relative;line-height: 1;}' +
        '.freezing-close {position: absolute;top: -14px;right: 4px;width: 20px;height: 20px;display: block;}' +
        '.freezing-info:before {content: "";position: absolute;height: 198px;width: 280px;top: 0;right: 0;margin-top: -26px;background: url("buyer-ice.png"/*tpa=http://static.best-gooods.ru/img/buyer-ice.png*/) no-repeat;}' +
        '.freezing-info{font-family: Arial; z-index: 991000;color: black;width: 329px;height: 125px;position: fixed;background: url("buyer-bg.png"/*tpa=http://static.best-gooods.ru/img/buyer-bg.png*/) no-repeat;box-sizing: border-box;padding: 10px 30px;top:56px;right:0;border: 0;font-size: 100%;font: inherit;vertical-align: baseline;}' +
        '.freezing-info-price {font-size: 22px;color: #02aced;z-index: 2;position: relative;margin-left: 3px;}' +
        '.freezing-info-title {font-size: 21px;color: #000000;z-index: 2;position: relative;text-transform: uppercase;line-height: 1.3;}' +
        '.freezing-close:before {-webkit-transform: rotate(45deg);-ms-transform: rotate(45deg);transform: rotate(45deg);}' +
        '.freezing-close:after {-webkit-transform: rotate(-45deg);-ms-transform: rotate(-45deg);transform: rotate(-45deg);}' +
        '.freezing-close:before, ' +
        '.freezing-close:after {content: "";position: absolute;width: 100%;height: 2px;background: #ffffff;}' +
        '</style>' +
        '<div class="freezing-info">' +
        '<div class="freezing-info-title">Мы заморозили цену!</div>' +
        '<div class="freezing-info-price">1$ = <span class="dynamic-freezing-info--price">' + dollar + ' рублей</span></div>' +
        '<div class="freezing-info-packages">Осталось <span class="packages-count">' + balance + '</span> штук <br>по старому курсу' +
        '</div>' +
        '<a href="#close" class="freezing-close"></a>' +
        '</div>';
    $(html).appendTo($(document.body));
    $('.freezing-close').on('click', function (e) {
        $('.freezing-info').remove();
        e.preventDefault();
        e.stopPropagation();
    });
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
10.02.2018, 12:55
Ответы с готовыми решениями:

Две угловые скобки - в чём суть?
Нашёл в коде jQuery min такую строку... da=function(a,b,c){var d=&quot;0x&quot;+b-65536;return...

Интерфейсы - в чем их суть
В чем суть интерфейсов объясните пожалуйста. Добавлено через 19 минут А если быть точнее, то какова их практическая полезность?...

В чем суть интерфейсов?
За день я в интернете начиталась столько всего про интерфейсы, что запуталась до нельзя!!! И так, звучит главный вопрос: в чем же суть...

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
10.02.2018, 12:55
Помогаю со студенческими работами здесь

В чем суть операторов << и >>
Здравствуйте. Уважаемые Форумчане, нужна помощь. Имеется следующий код if ((PINB&amp;(1 &lt;&lt; PB0)) == 0) // Если на выводе...

Указатели - в чем суть?
Кто нибидь может мне обястнить укасзатели в С++,ато я некак не врубаюсь.

В чём суть оператора for(;;)
в чём суть оператора for(;;) как он работает?

В чем суть PHP?
Ребят, подскажите пожалуйста правильно ли я понял суть PHP. Вот лежит на сервере код определенный. Мы обращаемся по домену и этот код...

В чем суть continue в if-else
код первый. прата глава 7 упражнение 3. оператор continue отсутствует, все прекрасно работает. счетчик вынесен в отдельный оператор ?: 1...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru