Home > Web Front-end > JS Tutorial > body text

JavaScript implements pressing Ctrl key to open a new page_javascript skills

WBOY
Release: 2016-05-16 16:37:27
Original
1984 people have browsed it

(Translator’s Note: This article solves the problem of using JS to open a new page when pressing the Ctrl key)

In the simplified HTML5 specification, multiple DIVs and/or other block-level elements are allowed to be included in the A tag. Now as long as the block element is wrapped with the tag, you can solve the problem of using JavaScript to listen and Call window.location to implement page jump (redirect) function.

But there are situations where this packaging form of using tags does not work well - for example, there are some tags in a certain block element (block), in this case we just want to Jump to a given address only when clicking on other parts of parent except .

Of course, our needs can also be achieved with a simple listener like the following:

Copy code The code is as follows:

someElement.addEventListener('click', function(e) {
// The URL address can be anything, or you can use other codes to specify it.
// The `data-src` DOM attribute of the element is used here (attribute)
​ window.location = someElement.get('data-url');
});

…But this sometimes has a bad user experience. When you hold down the CTRL key (COMMAND key on Mac) and click with the mouse, it will open the link in the same (tab) window. Knowing that there is this problem, you must have thought about how to solve it. We can achieve this goal by modifying a small amount of code. Hurry up and spend some time to repair your listener:

Copy code The code is as follows:

someElement.addEventListener('click', function(e) {
// Get URL
var url = someElement.get('data-url');
// Determine whether the CTRL key is pressed
If(e.metaKey || e.ctrlKey || e.button === 1) {
          window.open(url);
} else {
          window.location = url;
}
});

The original author has implemented this function on the http://davidwalsh.name/ website. You should also remember this when using window.location for page redirection. This is a small code improvement, but a very important improvement in usability!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template