Toggle divs without using Javascript

后端 未结 11 2026
日久生厌
日久生厌 2020-12-06 10:19

I\'d like to toggle a

, but my requirement is that it must work with javascript turned off. I would like to select a hyperlink that sta
11条回答
  •  春和景丽
    2020-12-06 11:04

    For a little more polished version of the accepted answer, a common practice is to combine a hidden checkbox + label to be able to have a clickable label on screen that maps to a hidden backing value that is available to both JavaScript (.checked) and to CSS (:checked)

    
    
    
    Unexpected StackOverflow

    By putting our checkbox first, we can drive CSS decisions based on the :checked selector. We can grab subsequent elements with the adjacent sibling select + or the general sibling selector ~

     /* always hide the checkbox */
    .css-toggle-switch { display: none; }
    
    /* update label text to reflect state */
    .css-toggle-switch         + label:before { content: "Hide "; }
    .css-toggle-switch:checked + label:before { content: "Show "; }
    
     /* conditionally hide content when checked */
    .css-toggle-switch:checked ~ .css-toggle-content  { display: none; }
    
    /* make the label look clickable */
    .css-toggle-switch + label {
       cursor: pointer;
      -webkit-touch-callout: none;
        -webkit-user-select: none;
           -moz-user-select: none;
            -ms-user-select: none;
                user-select: none;
    }
    

    Working Demo in jsFiddle & StackSnippets

    .css-toggle-switch { display: none; }
    .css-toggle-switch         + label:before { content: "Hide "; }
    .css-toggle-switch:checked + label:before { content: "Show "; }
    .css-toggle-switch:checked ~ .css-toggle-content  { display: none; }
    
    .css-toggle-switch + label {
       cursor: pointer;
      -webkit-touch-callout: none;
        -webkit-user-select: none;
           -moz-user-select: none;
            -ms-user-select: none;
                user-select: none;
    }
    
    
    
    /* just some styles to make the demo a little more pleasant */
    .btn {
      padding: 5px 10px;
      background: white;
      border: 1px solid grey;
      border-radius: 3px;
      width: 130px;
      display: inline-block;
      text-align: center;
    }
    .btn:hover {
      background: #e6e6e6;
      -webkit-box-shadow: inset 0 -1px 0 #ffffdffffd;
         -moz-box-shadow: inset 0 -1px 0 #ffffdffffd;
              box-shadow: inset 0 -1px 0 #ffffdffffd;
    }
    .panel {
        padding: 15px;
        background: #ffe06d;
        border: 1px solid #d69e01;
        border-radius: 3px;
    }
    pre {
      padding: 5px;
      margin-bottom: 0;
      background: #eaeaea;
      border: 1px solid grey;
        
    }
    Unexpected StackOverflow

提交回复
热议问题