【问题标题】:Make onclick function in HTML to do 2 functions在 HTML 中制作 onclick 函数来执行 2 个功能
【发布时间】:2018-10-06 11:27:16
【问题描述】:

这就是我正在做的代码

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

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

【问题讨论】:

  • 这不是一个按钮。这是一个锚。你应该使用&lt;button&gt;

标签: javascript html css onclick


【解决方案1】:

你可以设置一个全局标志

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>

【讨论】:

  • 比我的解决方案更好,+1
【解决方案2】:

简单,使用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

}

【讨论】:

  • arg 是从哪里来的? O.o
  • Switch 这里“css/blue.css”是函数setStyleSheet的参数
  • 所以代码是 Switch ..?
  • 抱歉,这些东西真的很慢
  • 不用担心,你将如何学习,顺便说一下 arg 被称为参数,它是你赋予函数的值,你需要像这样设置链接 Switch,"Arg" 是函数参数的占位符。如果您不明白我的意思,我建议您使用编程教程。
【解决方案3】:

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

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>

【讨论】:

    【解决方案4】:

    我建议不要使用 href="#"。这将提供丑陋的网址。 如果你使用锚更好使用

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

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

    【讨论】:

      【解决方案5】:

      一种可行的方法(取决于样式表的复杂性)是更新 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.

      参考资料:

      参考书目:

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-12
        • 1970-01-01
        • 2017-02-11
        • 2020-10-28
        相关资源
        最近更新 更多