如何使用Bootstrap 5从jQuery切换到Vanilla JavaScript

曾歌者
2023-12-01

Bootstrap 5 is a free and open-source CSS framework directed at responsive, mobile-first front-end web development.

Bootstrap 5是一个免费的开源CSS框架,专门用于响应式,移动优先的前端Web开发。

In case you didn't know, Bootstrap 5 alpha has been officially launched. It has removed jQuery as a dependency, has dropped support for Internet Explorer 9 and 10, and brings some awesome updates for the Sass files, markup, and a new Utility API.

如果您不知道, Bootstrap 5 alpha已正式启动 。 它已删除了jQuery的依赖关系,放弃了对Internet Explorer 9和10的支持,并为Sass文件,标记和新的Utility API带来了一些很棒的更新。

This tutorial will show you how to start using VanillaJS instead of jQuery when building websites using the newest version of Bootstrap 5.

本教程将向您展示在使用最新版本的Bootstrap 5构建网站时如何开始使用VanillaJS而不是jQuery。

入门 (Getting started)

You will need to include Bootstrap 5 in your project. There are several ways to do this, but to keep it simple we will include the framework via CDN.

您将需要在项目中包含Bootstrap 5。 有几种方法可以做到这一点,但为简单起见,我们将通过CDN包含该框架。

First of all, let's create a blank index.html page inside a project folder:

首先,让我们在项目文件夹中创建一个空白的index.html页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bootstrap 5 Vanilla JS tutorial by Themesberg</title>
</head>
<body>
    
</body>
</html>

Include the bootstrap.min.css stylesheet before the end of your <head> tag:

<head>标记的末尾包括bootstrap.min.css样式表:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">

Afterwards include the Popper.js library and the main Bootstrap JavaScript file before the end of your <body> tag:

然后在<body>标记的末尾包含Popper.js库和Bootstrap主JavaScript文件:

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>

Curious what the integrity and crossorigin attributes mean? Here's the explanation:

好奇integritycrossorigin属性的含义是什么? 解释如下:

Integrity attribute: allows the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

完整性属性允许浏览器检查文件源,以确保如果源已被操纵,则从不加载代码。

Crossorigin attribute: is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'.

Crossorigin属性在使用“ CORS”加载请求时存在,现在,当不从“ same-origin”加载时,这是SRI检查的要求。

Great! Now we have successfully included the newest version of Bootstrap in our project. One of the obvious differences is that we no longer had to require jQuery as a dependency, saving about 82.54 KB in bandwidth if in a minified state.

大! 现在,我们已经在项目中成功包含了最新版本的Bootstrap。 明显的区别之一是,我们不再需要将jQuery作为依赖项,如果处于缩小状态,则可以节省大约82.54 KB的带宽。

从jQuery切换到Vanilla JS (Switching from jQuery to Vanilla JS)

Before we get started with this section, you should know that using Bootstrap 5 with jQuery is still possible according to the official documentation.

在开始本节之前,您应该知道根据官方文档仍然可以将Bootstrap 5与jQuery一起使用。

We recommend using Vanilla JavaScript if the only reason you've been using jQuery was for the query selector, because you can do the same thing with the document.querySelector('#element') as if it was $('#element').

如果您一直使用jQuery的唯一原因是查询选择器,我们建议您使用Vanilla JavaScript,因为您可以对document.querySelector('#element')相同的操作,就好像它是$('#element')

The first step is to create a JavaScript file and include it before the end of the body tag but after the other two includes:

第一步是创建一个JavaScript文件,并将其包含在body标签末尾之前,但在其他两个之后包括:

<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
<script src="js/app.js"></script>

So when do you need to actually use Javascript with Bootstrap 5? There are certain components in the framework that work only if they are initialized via Javascript, such as tooltips, popovers and toasts.

那么什么时候需要在Bootstrap 5中实际使用Javascript? 框架中的某些组件仅在通过Javascript初始化时才有效,例如工具提示,弹出窗口和吐司。

Furthermore, with components such as modals, dropdowns, and carousels you may want to be able to programmatically change them based on a user action or application logic.

此外,对于模态,下拉菜单和轮播等组件,您可能希望能够根据用户操作或应用程序逻辑以编程方式更改它们。

通过Vanilla JavaScript初始化工具提示 (Initializing tooltips via Vanilla JavaScript)

We all love tooltips, but they don't work unless they are initialized via JavaScript. Let's first start by creating a tooltip element inside our index.html file:

我们都喜欢工具提示,但是除非通过JavaScript初始化,否则它们不会起作用。 首先,我们在index.html文件中创建一个工具提示元素:

<button id="tooltip" type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="top" title="Tooltip on top">
    Tooltip on top
</button>

Hovering over the button will not show the tooltip, because by default it is an opt-in feature of Bootstrap and it needs to be initialized manually using JavaScript. If you want to do it with jQuery, here's how it would look:

将鼠标悬停在按钮上不会显示工具提示,因为默认情况下,它是Bootstrap的启用功能,需要使用JavaScript手动对其进行初始化。 如果要使用jQuery,请按以下说明进行操作:

$('#tooltip').tooltip();

Using Vanilla JS you would need to use the following code to enable the tooltip:

使用Vanilla JS,您需要使用以下代码来启用工具提示:

var tooltipElement = document.getElementById('tooltip');
var tooltip = new bootstrap.Tooltip(tooltipElement);

What the code above does it that it selects the element with the unique id of "tooltip" and then creates a Bootstrap tooltip object. You can then use that to manipulate the state of the tooltip, such as showing or hiding the tooltip programmatically.

上面的代码执行的操作是选择唯一ID为“ tooltip”的元素,然后创建一个Bootstrap tooltip对象。 然后,您可以使用它来操作工具提示的状态,例如以编程方式显示或隐藏工具提示。

Here's an example on how you could show/hide it via methods:

这是一个有关如何通过方法显示/隐藏它的示例:

var showTooltip = true;
if (showTooltip) {
    tooltip.show();
} else {
    tooltip.hide();
}

If you would like to enable all of the tooltips you could also use the following code:

如果要启用所有工具提示,则还可以使用以下代码:

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
});

What happens here is that we select all of the elements that have the data-toggle="tooltip" attribute and value and initialize a tooltip object for each one. It also saves them to a tooltipList variable.

这里发生的是,我们选择所有具有data-toggle="tooltip"属性和值的元素,并为每个元素初始化一个tooltip对象。 还将它们保存到tooltipList变量。

使用Collapse JavaScript方法切换元素的可见性 (Toggle the visibility of your elements using the Collapse JavaScript methods)

The collapse feature on Bootstrap is another very handy way to show and hide elements via data attributes or JavaScript.

Bootstrap的折叠功能是通过数据属性或JavaScript显示和隐藏元素的另一种非常方便的方法。

Here's an example of how we can show or hide a card when a certain button is being clicked. Let's first create the HTML markup:

这是一个示例,显示了当单击某个按钮时如何显示或隐藏卡片。 首先创建HTML标记:

<button id="toggleCardButton" type="button" class="btn btn-primary mb-2">Toggle Card</button>
    <div id="card" class="card collapse show" style="width: 18rem;">
        <img src="https://dev-to-uploads.s3.amazonaws.com/i/rphqzfoh2cbz3zj8m8t1.png" class="card-img-top" alt="...">
        <div class="card-body">
            <h5 class="card-title">Freecodecamp.org</h5>
            <p class="card-text">Awesome resource to learn programming from.</p>
            <a href="#" class="btn btn-primary">Learn coding for free</a>
        </div>
    </div>

So we created a button with the id toggleCardButton and a card with the id card. Let's start by selecting the two elements:

因此,我们创建了一个带有id toggleCardButton的按钮和一个带有id card 。 让我们从选择两个元素开始:

var toggleButton = document.getElementById('toggleCardButton');
var card = document.getElementById('card');

Then we need to create a collapsable object using the newly selected card element:

然后,我们需要使用新选择的card元素创建可折叠对象:

var collapsableCard = new bootstrap.Collapse(card, {toggle: false});

What the toggle:false flag does is that it keeps the element visible after creating the object. If not present, it would hide the card by default.

toggle:false标志的作用是在创建对象之后使元素保持可见。 如果不存在,默认情况下它将隐藏卡。

Now we need to add an event listener for the button for the click action:

现在,我们需要为click动作的按钮添加一个事件侦听器:

toggleButton.addEventListener('click', function () {
    // do something when the button is being clicked
});

And lastly we need to toggle the card using the collapsable object that we initialized like this:

最后,我们需要使用初始化后的可折叠对象来切换卡,如下所示:

toggleButton.addEventListener('click', function () {
    collapsableCard.toggle();
});

That's it! Now the card will be shown/hidden whenever the button is clicked. Of course all of this could've been done using the data attributes feature from Bootstrap, but you may want to toggle certain elements based on an API call or a logic in your application.

而已! 现在,只要单击该按钮,卡就会显示/隐藏。 当然,所有这些都可以使用Bootstrap的数据属性功能完成,但是您可能希望基于API调用或应用程序中的逻辑切换某些元素。

结论 (Conclusion)

If you have followed along this tutorial you should now be able to use the most popular CSS framework without the need of requiring jQuery in your project. This lets you save up to 85 KB of data and makes your website faster! Congratulations 

如果您已按照本教程进行操作,则现在应该可以使用最受欢迎CSS框架,而无需在项目中使用jQuery。 这样最多可以保存85 KB的数据 ,并使您的网站更快! 恭喜

If you appreciate this tutorial and like using Bootstrap as a CSS framework for your projects, I invite you to check out some of the free and premium Bootstrap themes, templates, and UI Kits that we build at Themesberg ❤️

如果您喜欢本教程,并且喜欢将Bootstrap用作项目CSS框架,我邀请您查看我们在Themesberg❤️构建的一些免费和高级的Bootstrap主题,模板和UI套件。

翻译自: https://www.freecodecamp.org/news/bootstrap-5-vanilla-js-tutorial/

 类似资料: