I am trying to modify the href
attribute when a user clicks on a link. I'm using a script called stylesheetswitcher to switch CSS styles and would like to jump between 2 styles while clicking one link.
Here is the link HTML:
<a href="javascript:chooseStyle('style1')"">switch style</a>
I want the href
change to "style2" when clicked.
Thanks for clarifying your requirements.
As mentioned on the page for styleswitcher JS , there are only a few things you need to do to get this working:
title
attributes to your <link>
tags in your head Let's say you have the following stylesheet links:
<link rel="stylesheet" href="css/style1.css">
<link rel="alternate stylesheet" href="css/style2.css">
You need to mark them by adding title
attributes, like so:
<link rel="stylesheet" href="css/style1.css" title="style1">
<link rel="alternate stylesheet" href="css/style2.css" title="style2">
function swapStyles () {
if ( this.getAttribute('data-active-style').value === 'style1' ) {
// Switch styles
chooseStyle('style2',30);
// Set the active style
this.setAttribute('data-active-style','style2');
} else {
// Switch styles
chooseStyle('style1',30);
// Set the active style
this.setAttribute('data-active-style','style1');
}
return this;
}
<a>
You can do this with the HTML onclick
attribute
<a href="javascript:;" onclick="swapStyles()">switch styles</a>
Or, you can add an event listener in Javascript:
document.querySelectorAll('a')[0].addEventListener('click', function () {
swapStyles();
}, true);
It's better to make something like a toggle function, like so:
function toggleStyle () {
if ( this.className.indexOf('style1') > -1 )
this.className = 'style2';
else
this.className = 'style1';
}
Also, you should take that Javascript out of the href
attribute. Instead, add an event listener in your Javascript:
function toggleStyle () {
if ( this.className.indexOf('style1') > -1 )
this.className = 'style2';
else
this.className = 'style1';
}
// Wait for window to load
window.onload = function () {
// Add event listener
document.querySelectorAll('a')[0].addEventListener('click', toggleStyle, true);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.