search

Home  >  Q&A  >  body text

javascript - js div highlight reminder

There are 10 ps, ​​and there will be a highlight prompt when clicking, but you can only click two at a time. It is not a checkbox but a simple p containing content, or 10 different paragraphs of text. How to implement it with js?

我想大声告诉你我想大声告诉你2740 days ago685

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-19 10:47:53

    General idea

    • Add a checked attribute to each p, the default is false,
      p[i].checked = false;

    • Change the checked attribute of current p while clicking, p[i].checked = !p[i].checked

    • While clicking p, traverse all the checked attributes of p. If two of them are checked, return false to exit the function. Otherwise, negate and assign the checked attribute of p. There are also some specific conditions to judge, and you can come up with it slowly according to your ideas.

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:47:53

    Give you an example - -
    View the example directly: https://jsfiddle.net/677a1m6z/1/

    html

        <p class="demo">高亮1</p>
        <p class="demo">高亮2</p>
        <p class="demo">高亮3</p>
        <p class="demo">高亮4</p>
        <p class="demo">高亮5</p>
        <p class="demo">高亮6</p>
        <p class="demo">高亮7</p>
        <p class="demo">高亮8</p>
        <p class="demo">高亮9</p>
        <p class="demo">高亮10</p>

    css

        .demo {
            width: 140px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid;
            margin-bottom: 5px;
            box-sizing: border-box;
        }
    
        .active {
            background-color: #f55;
            color: #fff;
            border: 0;
        }

    js

     $(document).on('click', '.demo', function() {
            $(this).addClass('active');
            var len = $('.active').length;
            //初始化处理最开始的两次点击
            if (len === 1) {
                $(this).addClass('c-1');
            }
            if (len === 2) {
                $(this).addClass('c-2');
            }
            //当已经有两个高亮,再次点击会取消最靠前一次点击的高亮
            //例如:先点击4和6,再点2则最靠前的4会被取消,再点7则最靠前的6又会被取消
            if (len === 3) {
                $('.c-1').removeClass('c-1 active');
                $('.c-2').removeClass('c-2').addClass('c-1');
                $(this).removeClass('c-1').addClass('c-2');
            }
        });

    Note: The reason why c-1 and c-2 identifiers are used here instead of index to get active elements, such as $('.active').eq(0), is because index has a sequential order, which will lead to clicks. One of the elements before or after a highlighted element is always invalid.

    reply
    0
  • Cancelreply