在HTML中使用onclick功能来完成2个功能

问题描述 投票:0回答:5

所以这就是我正在做的代码

<a onclick="setStyleSheet('css/blue.css')" href="#">Switch</a>
<a onclick="setStyleSheet('css/red.css')" href="#">Switch</a>

点击它将切换到蓝色主题。但我想保持按钮相同。而不是使用2个按钮。我只想要一个Switch按钮变为蓝色,然后如果我再次单击该按钮,它将变为红色。反正有没有这样做?提前谢谢!

javascript html css onclick
5个回答
2
投票

您可以设置全局标志

window.blueTheme = true
function setStyleSheet() {
    var styleSheetToBeSet = window.blueTheme ? "css/red.css" : "css/blue.css"
    window.blueTheme = !window.blueTheme

    // your code here
}

当然,您可以将blueTheme更改为主题和商店主题名称而不是布尔变量。

然后只需调用不带参数的函数:

<a onclick="setStyleSheet()" href="#">Switch</a>

0
投票

简单,使用if循环来比较参数

function StyleSheet(arg) {
    if (arg == "css/blue.css") {
        var styleSheetToBeSet = "css/red.css";
     }
   else {
       var styleSheetToBeSet = "css/blue.css";
   }
   //set style sheet here with js

}

0
投票

我会使用另一个辅助函数并首先设置一些条件。

function setElement(){
  var style = document.styleSheets[0]; //set the index
  if(style.href ==='css/blue.css'){
    style.href = 'css/red.css';
  }else if (style.href ==='css/red.css'){
    style.href = 'css/blue.css';
   }else{
   console.log('error');
   }
}

<a onclick="setElement();" href="#">Switch</a>

0
投票

我建议不要使用href =“#”。这将给uggly网址。如果你使用锚更好用

<a onclick="setStyleSheet('....')" href="javascript:void(0)">Switch</a>

另一种选择是在你的javascript函数中使用event.preventDefault();


0
投票

一种可行的方法(取决于样式表的复杂性)是更新CSS自定义属性以更新要更改或编辑的属性:

// defining the colours to be used (the approach taken in these
// code snippets allows for other values to be added to this
// Array to extend the number of colours/values used):
let cssStyles = ['blue', 'red'],

  // defining the function (using Arrow syntax, since
  // we don't need to use the 'this' object within):
  modifyCSS = (styles) => {

    // 'styles': the Array of colours passed into the function.

    // here we find the root-element of the document:
    let root = document.querySelector(':root'),

      // we retrieve the current value of the '--colorValue'
      // CSS property defined in that Node's CSS (if present):
      current = root.style.getPropertyValue('--colorValue'),

      // and, because this property-value is a String, we search
      // the Array of colours to retrieve the index of the current
      // colour:
      index = styles.indexOf(current);

    // here we update the '--colorValue' custom property to the
    // property held in the next index of the Array; or to the
    // value held at the Array's zeroth/first index:
    root.style.setProperty('--colorValue', styles[++index % styles.length]);
  }

// binding the function to the click event on the '#updatecss' button:
document.querySelector('#updatecss').addEventListener('click', (e) => modifyCSS(cssStyles) );

let cssStyles = ['blue', 'red'],
  modifyCSS = (event, styles) => {
    let root = document.querySelector(':root'),
      current = root.style.getPropertyValue('--colorValue'),
      index = styles.indexOf(current);
    root.style.setProperty('--colorValue', styles[++index % styles.length]);
  }

document.querySelector('#updatecss').addEventListener('click', (e) =>  modifyCSS(e, cssStyles) );
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wrapper {
  display: grid;
  grid-template-columns: 40vw 40vw;
  width: 80vw;
  margin: auto;
  grid-gap: 4px;
}

.wrapper>div {
  color: var(--colorValue, black);
  border: 2px solid currentColor;
  grid-column: 1/-1;
}
<div class="wrapper">
  <button id="updatecss">Switch CSS</button>
  <div>element 1</div>
  <div>element 2</div>
  <div>element 3</div>
  <div>element 4</div>
</div>

JS Fiddle demo

鉴于您的问题需要新的样式表,并且可能是您的需求的简化版本,更新CSS自定义属性以满足您的需求可能更加困难。但是,我们可以使用样式表名称数组的类似方法:

// CSS stylesheet filenames:
let stylesheets = ['blue.css', 'red.css'],

  // named function, using Arrow syntax as above, to change
  // the stylesheets:
  modifyCSS = (sheets) => {

    // finding the relevant <link> element:
    let link = document.querySelector('.linkedResource'),

      // finding the index of the last '/' character in
      // the href property-value of the <link>; adding 1
      // so that the last slash is included in the 'path'
      // and not the 'file':
      lastSlashIndex = link.href.lastIndexOf('/') + 1,

      // here we find the substring of the href up to,
      // and including, the last '/' character:
      path = link.href.substring(0, lastSlashIndex),

      // finding the filename (based on the assumption
      // that the filename follows the last '/' character):
      file = link.href.slice(lastSlashIndex),

      // finding the index of the current filename in the
      // Array of filenames:
      currentSheetIndex = sheets.indexOf(file);

    // updating the href of the <link> element to be equal
    // to the concatenated value of the path and the
    // filename held at the next, or first, index of the Array:
    link.href = path + sheets[++currentSheetIndex % sheets.length];
  };

document.querySelector('#updatecss').addEventListener('click', () => modifyCSS(stylesheets));

let stylesheets = ['blue.css', 'red.css'],
  modifyCSS = (sheets) => {
    let link = document.querySelector('.linkedResource'),
      lastSlashIndex = link.href.lastIndexOf('/') + 1,
      path = link.href.substring(0, lastSlashIndex),
      file = link.href.slice(lastSlashIndex),
      currentSheetIndex = sheets.indexOf(file);
    link.href = path + sheets[++currentSheetIndex % sheets.length];
  };

document.querySelector('#updatecss').addEventListener('click', () => modifyCSS(stylesheets));
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wrapper {
  display: grid;
  grid-template-columns: 40vw 40vw;
  width: 80vw;
  margin: auto;
  grid-gap: 4px;
}

.wrapper>div {
  color: var(--colorValue, black);
  border: 2px solid currentColor;
  grid-column: 1/-1;
}
<link rel="stylesheet" href="https://www.davidrhysthomas.co.uk/linked/blue.css" class="linkedResource" />
<div class="wrapper">
  <button id="updatecss">Switch CSS</button>
  <div>element 1</div>
  <div>element 2</div>
  <div>element 3</div>
  <div>element 4</div>
</div>

JS Fiddle demo

参考文献:

参考书目:

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.