【问题标题】:How to get the width on where the mouse clicks a div?如何获取鼠标单击 div 的宽度?
【发布时间】:2020-03-30 02:16:53
【问题描述】:

我想使用 HTML/CSS/JS 让 <div> 将其颜色更改为特定宽度。这个特定的长度取决于它在<div> 中的点击位置。

例子:

我会给出代码,但它只是<div>
我不知道如何使用 CSS/JS 来检测鼠标在 <div> 上的点击位置(即宽度大小)。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    你可以这样实现

    function changeWidth(event) {
      let outerDiv = document.getElementById('outerDiv');
      document.getElementById('innerDiv').style.width = event.clientX-outerDiv.offsetLeft+'px';
    }
    #outerDiv {
      width: 400px;
      height:200px;
      border: 1px solid black;
    }
    #innerDiv {
      width: 0px;
      height: 200px;
      background-color: red;
    }
    <div id = 'outerDiv' onclick = 'changeWidth(event)'>
      <div id = 'innerDiv' ></div>
    </div>

    您已经检查了使用el.offSetLeft可以获得的外箱位置

    【讨论】:

    • 不知道是不是我的浏览器,但是鼠标点击的宽度好像不太准确。
    • @user12055579 这是因为正文的边距。现在试试,我已经更新了答案。
    • 应该计算边界
    【解决方案2】:

    我愿意:

    //<![CDATA[
    /* js/external.js */
    let get, post, doc, html, bod, nav, M, I, mobile, S, Q, aC, rC, tC; // for use on other loads
    addEventListener('load', ()=>{
    get = (url, success, context)=>{
      const x = new XMLHttpRequest;
      const c = context || x;
      x.open('GET', url);
      x.onload = ()=>{
        if(success)success.call(c, JSON.parse(x.responseText));
      }
      x.send();
    }
    post = function(url, send, success, context){
      const x = new XMLHttpRequest;
      const c = context || x;
      x.open('POST', url);
      x.onload = ()=>{
        if(success)success.call(c, JSON.parse(x.responseText));
      }
      if(typeof send === 'object' && send && !(send instanceof Array)){
        if(send instanceof FormData){
          x.send(send);
        }
        else{
          const fd = new FormData;
          for(let k in send){
            fd.append(k, JSON.stringify(send[k]));
          }
          x.send(fd);
        }
      }
      else{
        throw new Error('send argument must be an Object');
      }
      return x;
    }
    doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
    mobile = nav.userAgent.match(/Mobi/i) ? true : false;
    S = (selector, within)=>{
      var w = within || doc;
      return w.querySelector(selector);
    }
    Q = (selector, within)=>{
      var w = within || doc;
      return w.querySelectorAll(selector);
    }
    aC = function(){
      const a = [].slice.call(arguments), n = a.shift();
      n.classList.add(...a);
      return aC;
    }
    rC = function(){
      const a = [].slice.call(arguments), n = a.shift();
      n.classList.remove(...a);
      return rC;
    }
    tC = function(){
      const a = [].slice.call(arguments), n = a.shift();
      n.classList.toggle(...a);
      return tC;
    }
    // you can ignore most of the above code (but it's useful, so keep it) - put below on a separate page on another load - except the load end
    const block = I('block'), colorStyle = block.firstChild.style;
    let down = false;
    function colorIt(e){
      if(down)colorStyle.width = e.clientX-e.target.offsetLeft+'px';
    }
    function touchMode(){
      block.onmousedown = block.onmousemove = undefined;
      block.ontouchstart = e=>{
        down = true; colorIt(e.touches[0]);
      }
      block.ontouchmove = e=>{
        colorIt(e.touches[0]);
      }
    }
    function mouseMode(){
      block.ontouchstart = block.ontouchmove = undefined;
      block.onmousedown = e=>{
        down = true; colorIt(e);
      }
      block.onmousemove = colorIt;
    }
    block.onclick = ()=>{
      down = false;
    }
    if(mobile){
      touchMode();
    }
    else{
      mouseMode();
    }
    }); // load end
    //]]>
    /* css/external.css */
    *{
      box-sizing:border-box; padding:0; margin:0;
    }
    html,body{
      width:100%; height:100%; background:#ccc;
    }
    .main{
      padding:10px;
    }
    #block{
      width:200px; height:75px; background:#fff; border:1px solid #000; cursor:pointer;
    }
    #block>div{
      width:0; height:100%; background:green;
    }
    <!DOCTYPE html>
    <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
      <head>
        <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
        <title>Title Here</title>
        <link type='text/css' rel='stylesheet' href='css/external.css' />
        <script src='js/external.js'></script>
      </head>
    <body>
      <div class='main'>
        <div id='block'><div></div></div>
      </div>
    </body>
    </html>

    【讨论】:

      【解决方案3】:

      使用background-image 创建颜色的简单方法。

      document.querySelector(".box").addEventListener("click", function(e){
        var position = e.clientX - this.getBoundingClientRect().left;
        this.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
      });
      .box {
        border: 2px solid #c3c3c3;
        height: 200px;
        width: 400px;
      }
      &lt;div class="box"&gt;&lt;/div&gt;

      e.clientX 是相对于窗口的位置。所以你可以使用.getBoundingClientRect().left中div的左边位置减去它得到准确的点击位置。


      如果您需要它来处理多个 div:

      1)为每个&lt;div&gt;添加内联onclick

      function colourBackground (e, div) {
        var position = e.clientX - div.getBoundingClientRect().left;
        div.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
      };
      .box {
        border: 2px solid #c3c3c3;
        height: 200px;
        width: 400px;
      }
      <div class="box" onclick="colourBackground(event, this)"></div>
      <div class="box" onclick="colourBackground(event, this)"></div>
      <div class="box" onclick="colourBackground(event, this)"></div>

      或者2)使用forEach循环给每个&lt;div&gt;添加点击事件

      document.querySelectorAll(".box").forEach(function(div) {
        div.addEventListener("click", function(e){
          var position = e.clientX - div.getBoundingClientRect().left;
          div.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
        });
      })
      .box {
        border: 2px solid #c3c3c3;
        height: 200px;
        width: 400px;
      }
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>

      【讨论】:

      • 线性渐变是如何工作的?如果您有一个背景 div 并将其宽度和颜色更改为完全红色,这是否完全相同?线性渐变会影响真实颜色吗?
      • 这是可能的,因为background-image 接受linear-gradient 并且不干扰background-color 属性。因此,您可以同时使用两者。
      • 另外,这仅适用于第一个 &lt;div class="select_option" &gt;,所有这些都具有公共类。
      • 使用多个 div 选项编辑了答案。
      【解决方案4】:

      有趣的问题。

      首先,使用它来获取 div 的位置:https://stackoverflow.com/a/10445639/11444910

      然后在点击时获取鼠标位置:https://stackoverflow.com/a/23744762/11444910

      现在您可以知道您的 div 在哪里以及单击时鼠标在哪里,您应该能够知道您是否在 div 内部单击。然后将鼠标的 Y 位置应用于 div,并使用它来通知颜色变化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-10
        • 1970-01-01
        相关资源
        最近更新 更多