vanilla代码_如何将jQuery代码转换为Vanilla JS

vanilla代码

jQuery was once one of the most popular JS libraries available. It solved a lot of problems, like making DOM manipulation and Ajax calls standard across all the different browsers, which all handled JavaScript slightly differently.

jQuery曾经是最流行的JS库之一。 它解决了很多问题,例如在所有不同的浏览器上都使DOM操作和Ajax调用成为标准,它们对JavaScript的处理略有不同。

A lot of jQuery's once cutting edge features have made it into vanilla JavaScript, so there's no need to load an entire library for just a few functionalities. Given this, it's not uncommon that one of your tasks on the job will be to rewrite jQuery into vanilla JavaScript.

许多jQuery曾经具有的最先进的功能已将其纳入原始JavaScript中,因此无需出于某些功能就加载整个库。 鉴于此,工作中的一项任务是将jQuery重写为原始JavaScript并不少见。

如何将jQuery重写为Vanilla JS (How to rewrite jQuery into vanilla JS)

Imagine you have the following code:

假设您有以下代码:

<div class="m1 menu">
    <div id="menu-center">
        <ul>
            <li><a class="active" href="#home">Home</a>

            </li>
            <li><a href="#portfolio">Portfolio</a>

            </li>
            <li><a href="#about">About</a>

            </li>
            <li><a href="#contact">Contact</a>

            </li>
        </ul>
    </div>
</div>
<div id="home"></div>
<div id="portfolio"></div>
<div id="about"></div>
<div id="contact"></div>
body, html {
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
}
.menu {
    width: 100%;
    height: 75px;
    background-color: rgba(0, 0, 0, 1);
    position: fixed;
    background-color:rgba(4, 180, 49, 0.6);
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
.light-menu {
    width: 100%;
    height: 75px;
    background-color: rgba(255, 255, 255, 1);
    position: fixed;
    background-color:rgba(4, 180, 49, 0.6);
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
#menu-center {
    width: 980px;
    height: 75px;
    margin: 0 auto;
}
#menu-center ul {
    margin: 15px 0 0 0;
}
#menu-center ul li {
    list-style: none;
    margin: 0 30px 0 0;
    display: inline;
}
.active {
    font-family:'Droid Sans', serif;
    font-size: 14px;
    color: #fff;
    text-decoration: none;
    line-height: 50px;
}
a {
    font-family:'Droid Sans', serif;
    font-size: 14px;
    color: black;
    text-decoration: none;
    line-height: 50px;
}
#home {
    background-color: grey;
    height: 100%;
    width: 100%;
    overflow: hidden;
    background-image: url(images/home-bg2.png);
}
#portfolio {
    background-image: url(images/portfolio-bg.png);
    height: 100%;
    width: 100%;
}
#about {
    background-color: blue;
    height: 100%;
    width: 100%;
}
#contact {
    background-color: red;
    height: 100%;
    width: 100%;
}
$(document).ready(function () {
    $(document).on("scroll", onScroll);
    
    //smoothscroll
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        $(document).off("scroll");
        
        $('a').each(function () {
            $(this).removeClass('active');
        })
        $(this).addClass('active');
      
        var target = this.hash,
            menu = target;
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top+2
        }, 500, 'swing', function () {
            window.location.hash = target;
            $(document).on("scroll", onScroll);
        });
    });
});

function onScroll(event){
    var scrollPos = $(document).scrollTop();
    $('#menu-center a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#menu-center ul li a').removeClass("active");
            currLink.addClass("active");
        }
        else{
            currLink.removeClass("active");
        }
    });
}

When you scroll down the page, the navbar should change colors as you get to different sections:

向下滚动页面时,导航栏应随着进入不同部分而改变颜色:

The function that handles this is onScroll:

处理此功能的函数是onScroll

function onScroll(event){
    var scrollPos = $(document).scrollTop();
    /* console.log(scrollPos); */
    $('#menu-center a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#menu-center ul li a').removeClass("active");
            currLink.addClass("active");
        }
        else{
            currLink.removeClass("active");
        }
    });
}

To translate onScroll into vanilla JS, you have a few options.

要将onScroll转换为onScroll JS,您有几种选择。

选项1:使用在线编译器 (Option 1: Use an online compiler)

You can use an online tool like Google's Closure Compiler to compress the code and strip out any unnecessary jQuery.

您可以使用Google的Closure Compiler之类的在线工具来压缩代码并删除所有不必要的jQuery。

The problem is that you're still essentially left with jQuery code, so the browser would still need to load the library.

问题是您实际上仍然只剩下jQuery代码,因此浏览器仍然需要加载该库。

选项2:手动翻译代码 (Option 2: Manually translate the code)

The best option is to check out resources like You Don't Need jQuery and You Might Not Need jQuery before rewriting your jQuery code. You'll be able to find the native JS versions of the most popular jQuery methods, some of which you can use in your own code.

最好的选择是在重写jQuery代码之前先检查诸如“ 您不需要jQuery”和“ 您可能不需要jQuery”之类的资源。 您将能够找到最流行的jQuery方法的本机JS版本,其中一些可以在自己的代码中使用。

Here's the onScroll function in vanilla JS:

这是香草JS中的onScroll函数:

function onScroll(event) {
  var sections = [...document.querySelectorAll('#menu-center a')];
  var scrollPos = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  sections.forEach(function(currLink) {
    var val = currLink.getAttribute('href');
    var refElement = document.querySelector(val);
    if (refElement.offsetTop <= scrollPos && (refElement.offsetTop + refElement.offsetHeight > scrollPos)) {
      //document.querySelector('#menu-center ul li a').classList.remove('active');
      currLink.classList.add('active');
    } else {
      currLink.classList.remove('active');
    }
  });
}

document.addEventListener('scroll', onScroll);

翻译自: https://www.freecodecamp.org/news/how-to-translate-jquery-code-into-vanilla-js/

vanilla代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值