使用按钮的 CSS 操作



我正在尝试制作一个小的设置页面,用户可以在其中更改网站的外观,我希望他们能够单击一个按钮,网站 CSS 也随之更新(以及背景 colo(u(r(,我希望更改保存在所有页面上。

我该怎么做?

从您的问题中,我提出了一个更适合您的用例的解决方案,以更整洁的实现。

以以下代码为例;

<div id="container">
<div>
<h1>Page Header</h1>
<h3>Page Sub Header</h3>
<p>Page Content</p>
</div>
<div class="buttons">
<button id="default-theme" onclick="setTheme(event)">default</button>
<button id="theme-one" onclick="setTheme(event)">theme one</button>
<button id="theme-two" onclick="setTheme(event)">theme two</button>
</div>
</div>

在上面的代码中,您有一些无样式的元素和一些按钮来设置首选主题颜色。

您可以在CSS文件中设置主题颜色,如下所示。下面的代码是一个 SCSS 实现。查看代码Pen https://codepen.io/sirwhite/pen/mdbNjLG 上的实时解决方案

<style>
// Default theme color
.default-theme {
background: $default-bg;
}
.default-theme h1 {
color: $default-color;
}
.default-theme h3 {
color: $default-color;
}
.default-theme p {
color: $default-color;
}
// Theme One Colors
.theme-one {
background: $theme-one-bg;
}
.theme-one h1 {
color: $theme-one-color;
}
.theme-one h3 {
color: $theme-one-color;
}
.theme-one p {
color: $theme-one-color;
}
// Theme Two Colors
.theme-two {
background: $theme-two-bg;
}
.theme-two h1 {
color: $theme-two-color;
}
.theme-two h3 {
color: $theme-two-color;
}
.theme-two p {
color: $theme-two-color;
}
</style>

现在,使用javascript根据用户的选择设置主题颜色

var theme = '';
var container = document.getElementById('container');
window.addEventListener('load', function() {
if(localStorage.theme && localStorage.theme !== '') {
theme = localStorage.theme;
container.classList.add(theme);
}
else {
theme = 'default-theme';
}
});
function setTheme(event) {
theme = event.target.id ;
localStorage.theme = theme;
container.classList = [];
container.classList.add(theme);
}

可以使用 LocalStorage 在所有页面上保留选定的主题值。页面加载时,您可以检查是否设置了 localStorage 值,否则将主题设置为默认主题。

查看代码笔 https://codepen.io/sirwhite/pen/mdbNjLG 上的实时解决方案

你可以用javascript或jquery来做到这一点,方法是在点击按钮时调用一个函数。

我们的 HTML,请注意当我们单击按钮时我们如何调用myFunction

<h1 class="item blue">Hello World</h1>
<button onClick="myFunction()">Click Me</button>

一些基本的CSS:

.blue {
color: blue;
}
.red {
color: red;
}

我们的 Javascript 将根据已经存在的类添加一个类。我们可以更改目标变量以从其他元素中添加/删除类。

function myFunction() {
var target = document.querySelector('.item');
if (target.classList.contains('red')) {
target.classList.remove('red')
target.classList.add('blue')
} else if (target.classList.contains('blue')) {
target.classList.add('red')
target.classList.remove('blue')
}
}

这是一种非常千篇一律的方法,但它有效,您可以在此处采用相同的原则并将其应用于您的代码。

要在站点范围内使用此,只需使用单独的 javascript 文件并导入相同的 javascript 并在每个页面上调用相同的函数。

希望这对:)有所帮助

根据我对问题的理解,您想在单击按钮时更改背景颜色

<!DOCTYPE html>
<html>
<head>
<style>
.yellows {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<button id="btn">click me </button>
<script>
$('#btn').click(function() {
$('body').toggleClass( "yellows" );
});
</script>
</body>
</html>

最新更新