草庐IT

javascript - 滚动时元素转到错误的位置

coder 2023-08-12 原文

我正在使用来自 this website 的色轮选择器,我想出了一个问题。当我在色轮上方添加文本,然后向下滚动并更改色轮颜色时,色轮光标不包含在实际圆圈中。 (它在另一个地方做了一个假想的圆圈,色轮光标被限制在那个假想的圆圈内。)

另一个可能与第一个问题相关的问题是,如果您在浏览器中放大,(在 chrome 中:ctrl +)色轮光标会像固定元素一样保持位置,它会跟随滚动。

如何让色轮光标始终停留在圆圈内?

相关代码(JSFiddle中第210-211行):

hsv_mapCursor.style.left = ((x * r + colorDiscRadius + doc.body.scrollLeft + doc.documentElement.scrollLeft) - 1) + 'px';
hsv_mapCursor.style.top = ((y * r + colorDiscRadius + doc.body.scrollTop + doc.documentElement.scrollTop) - 1) + 'px';

JSFiddle

var Tools = {}, // provides functions like addEvent, ... getOrigin, etc.
  startPoint,
  currentTarget,
  currentTargetHeight = 0;
/* ----------------------------------- */
/* --------- Tool Functions ---------- */
/* ----------------------------------- */
function getOrigin(elm) {
  var box = (elm.getBoundingClientRect) ? elm.getBoundingClientRect() : {
      top: 0,
      left: 0
    },
    doc = elm && elm.ownerDocument,
    body = doc.body,
    win = doc.defaultView || doc.parentWindow || window,
    docElem = doc.documentElement || body.parentNode,
    clientTop = docElem.clientTop || body.clientTop || 0, // border on html or body or both
    clientLeft = docElem.clientLeft || body.clientLeft || 0;

  return {
    left: box.left + (win.pageXOffset || docElem.scrollLeft) - clientLeft,
    top: box.top + (win.pageYOffset || docElem.scrollTop) - clientTop
  };
}

function addEvent(obj, type, func) {
  addEvent.cache = addEvent.cache ||  {
    _get: function(obj, type, func, checkOnly) {
      var cache = addEvent.cache[type] || [];

      for (var n = cache.length; n--;) {
        if (obj === cache[n].obj && '' + func === '' + cache[n].func) {
          func = cache[n].func;
          if (!checkOnly) {
            cache[n] = cache[n].obj = cache[n].func = null;
            cache.splice(n, 1);
          }
          return func;
        }
      }
    },
    _set: function(obj, type, func) {
      var cache = addEvent.cache[type] = addEvent.cache[type] || [];

      if (addEvent.cache._get(obj, type, func, true)) {
        return true;
      } else {
        cache.push({
          func: func,
          obj: obj
        });
      }
    }
  };

  if (!func.name && addEvent.cache._set(obj, type, func) || typeof func !== 'function') {
    return;
  }

  if (obj.addEventListener) obj.addEventListener(type, func, false);
  else obj.attachEvent('on' + type, func);
}

function removeEvent(obj, type, func) {
  if (typeof func !== 'function') return;
  if (!func.name) {
    func = addEvent.cache._get(obj, type, func) || func;
  }

  if (obj.removeEventListener) obj.removeEventListener(type, func, false);
  else obj.detachEvent('on' + type, func);
}

Tools.getOrigin = getOrigin;
Tools.addEvent = addEvent;
Tools.removeEvent = removeEvent;









/* ---------------------------------- */
/* ---- HSV-circle color picker ----- */
/* ---------------------------------- */

// Create HSV-circle Relavent Variables
var hsv_map = document.getElementById('hsv_map'),
  colorDiskWrapper = document.getElementById('colorDiskWrapper'),
  colorDisc = document.getElementById('surface'),
  hsv_mapCover = document.getElementById('cover'),
  hsv_mapCursor = document.getElementById('hsv-cursor'),

  luminenceBarWrapper = document.getElementById('luminenceBarWrapper'),
  hsv_barBGLayer = document.getElementById('bar-bg'),
  hsv_barWhiteLayer = document.getElementById('bar-white'),
  luminanceBar = document.getElementById('luminanceBar'),
  hsv_barcursor = document.getElementById('hsv-barcursor'),
  hsv_barCursors = document.getElementById('hsv-barcursors'),
  hsv_barCursorsCln = hsv_barCursors.className,

  luminanceBarContext = luminanceBar.getContext("2d"),
  colorDiscHeight = colorDisc.offsetHeight,
  colorDiscRadius = colorDisc.offsetHeight / 2;



// generic function for drawing a canvas disc
var drawDisk = function(ctx, coords, radius, steps, colorCallback) {
    var x = coords[0] || coords, // coordinate on x-axis
      y = coords[1] || coords, // coordinate on y-axis
      a = radius[0] || radius, // radius on x-axis
      b = radius[1] || radius, // radius on y-axis
      angle = 360,
      rotate = 0,
      coef = Math.PI / 180;

    ctx.save();
    ctx.translate(x - a, y - b);
    ctx.scale(a, b);

    steps = (angle / steps) || 360;

    for (; angle > 0; angle -= steps) {
      ctx.beginPath();
      if (steps !== 360) ctx.moveTo(1, 1); // stroke
      ctx.arc(1, 1, 1, (angle - (steps / 2) - 1) * coef, (angle + (steps / 2) + 1) * coef);

      if (colorCallback) {
        colorCallback(ctx, angle);
      } else {
        ctx.fillStyle = 'black';
        ctx.fill();
      }
    }
    ctx.restore();
  },
  drawCircle = function(ctx, coords, radius, color, width) { // uses drawDisk
    width = width || 1;
    radius = [
      (radius[0] || radius) - width / 2, (radius[1] || radius) - width / 2
    ];
    drawDisk(ctx, coords, radius, 1, function(ctx, angle) {
      ctx.restore();
      ctx.lineWidth = width;
      ctx.strokeStyle = color || '#000';
      ctx.stroke();
    });
  };

if (colorDisc.getContext) {
  drawDisk( // HSV color wheel with white center
    colorDisc.getContext("2d"), [colorDisc.width / 2, colorDisc.height / 2], [colorDisc.width / 2 - 1, colorDisc.height / 2 - 1],
    360,
    function(ctx, angle) {
      var gradient = ctx.createRadialGradient(1, 1, 1, 1, 1, 0);
      gradient.addColorStop(0, 'hsl(' + (360 - angle + 0) + ', 100%, 50%)');
      gradient.addColorStop(1, "#FFFFFF");

      ctx.fillStyle = gradient;
      ctx.fill();
    }
  );
  drawCircle( // gray border
    colorDisc.getContext("2d"), [colorDisc.width / 2, colorDisc.height / 2], [colorDisc.width / 2, colorDisc.height / 2],
    '#555',
    3
  );
}


// draw the luminanceBar bar
var gradient = luminanceBarContext.createLinearGradient(0, 0, 0, colorDiscHeight);

gradient.addColorStop(0, "transparent");
gradient.addColorStop(1, "black");

luminanceBarContext.fillStyle = gradient;
luminanceBarContext.fillRect(0, 0, luminanceBar.offsetWidth, colorDiscHeight);









// Manage Color Wheel Mouse Events
var renderHSVPicker = function(color) { // used in renderCallback of 'new ColorPicker'
  var pi2 = Math.PI * 2,
    x = Math.cos(pi2 - color.hsv.h * pi2),
    y = Math.sin(pi2 - color.hsv.h * pi2),
    r = color.hsv.s * colorDiscRadius;

  hsv_mapCover.style.opacity = 1 - color.hsv.v;

  // this is the faster version...
  hsv_barWhiteLayer.style.opacity = 1 - color.hsv.s;
  hsv_barBGLayer.style.backgroundColor = 'rgb(' +
    color.hueRGB.r + ',' +
    color.hueRGB.g + ',' +
    color.hueRGB.b + ')';

  var doc = window.document;

  hsv_mapCursor.style.left = ((x * r + colorDiscRadius + doc.body.scrollLeft + doc.documentElement.scrollLeft) - 1) + 'px';
  hsv_mapCursor.style.top = ((y * r + colorDiscRadius + doc.body.scrollTop + doc.documentElement.scrollTop) - 1) + 'px';

  hsv_mapCursor.style.borderColor = hsv_barcursor.style.borderColor = color.RGBLuminance > 0.22 ? 'black' : 'white';
  hsv_barcursor.style.top = (((1 - color.hsv.v) * colorDiscRadius * 2 + doc.body.scrollTop + doc.documentElement.scrollTop) + -7) + 'px';
};


var myColor = new Colors(),
  doRender = function(color) {
    renderHSVPicker(color);
  },
  renderTimer,
  // those functions are in case there is no ColorPicker but only Colors involved
  startRender = function(oneTime) {
    if (oneTime) { // only Colors is instanciated
      doRender(myColor.colors);
    } else {
      renderTimer = window.setInterval(
        function() {
          doRender(myColor.colors);
          // http://stackoverflow.com/questions/2940054/
        }, 13); // 1000 / 60); // ~16.666 -> 60Hz or 60fps
    }
  },
  stopRender = function() {
    window.clearInterval(renderTimer);
  };





// Create Event Functions
var hsvDown = function(e) { // mouseDown callback
    var target = e.target || e.srcElement;

    if (e.preventDefault) e.preventDefault();

    //currentTarget = target.id ? target : target.parentNode;
    if (target === hsv_mapCover || target === hsv_mapCursor || target === hsv_barcursor) {
      currentTarget = target.parentNode;
    } else if (target === hsv_barCursors) {
      currentTarget = target;
    } else {
      return;
    }

    startPoint = Tools.getOrigin(currentTarget);
    currentTargetHeight = currentTarget.offsetHeight; // as diameter of circle

    Tools.addEvent(window, 'mousemove', hsvMove);
    hsv_mapCover.style.cursor = hsv_mapCursor.style.cursor = 'none';
    hsvMove(e);
    startRender();
  },
  hsvMove = function(e) { // mouseMove callback
    var r, x, y, h, s;

    if (currentTarget === colorDiskWrapper) { // the circle
      r = currentTargetHeight / 2;
      x = e.clientX - startPoint.left - r;
      y = e.clientY - startPoint.top - r;
      h = 360 - ((Math.atan2(y, x) * 180 / Math.PI) + (y < 0 ? 360 : 0));
      s = (Math.sqrt((x * x) + (y * y)) / r) * 100;
      myColor.setColor({
        h: h,
        s: s
      }, 'hsv');
    } else if (currentTarget === hsv_barCursors) { // the luminanceBar
      myColor.setColor({
        v: (currentTargetHeight - (e.clientY - startPoint.top)) / currentTargetHeight * 100
      }, 'hsv');
    }
  };

// Initial Rendering
doRender(myColor.colors);

// Adde Events To Objects
Tools.addEvent(hsv_map, 'mousedown', hsvDown); // event delegation
Tools.addEvent(window, 'mouseup', function() {
  Tools.removeEvent(window, 'mousemove', hsvMove);
  hsv_mapCover.style.cursor = hsv_mapCursor.style.cursor = hsv_barCursors.style.cursor = 'pointer';
  stopRender();
});
#wrapper {
  width: 500px;
  height: 500px;
  background-color: pink;
}
#hsv_map {
  width: 540px;
  height: 500px;
  position: absolute;
}
#colorDiskWrapper {
  border-radius: 50%;
  position: relative;
  width: 500px;
}
#cover {
  background-color: black;
  border-radius: 50%;
  cursor: pointer;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
#bar-bg,
#bar-white {
  position: absolute;
  right: 0;
  top: 0;
  width: 15px;
  height: 500px;
}
#bar-white {
  background-color: #fff;
}
#hsv-cursor {
  position: absolute;
  border: 2px solid #eee;
  border-radius: 50%;
  width: 9px;
  height: 9px;
  margin: -5px;
  cursor: pointer;
}
.no-cursor #hsv-cursor,
#hsv_map.no-cursor #cover {
  cursor: none;
  /* also works in IE8 */
  /*url(_blank.gif), url(_blank.png), url(_blank.cur), auto;*/
}
#luminanceBar {
  position: absolute;
  right: 0;
  top: 0;
}
#hsv-barcursors {
  position: absolute;
  right: -7.5px;
  width: 30px;
  top: 0;
  height: 500px;
  overflow: hidden;
  cursor: pointer;
}
#hsv-barcursor {
  position: absolute;
  right: 7.5px;
  width: 11px;
  height: 11px;
  border-radius: 50%;
  border: 2px solid black;
  margin-bottom: 5px;
}
<script src="https://rawgit.com/PitPik/colorPicker/master/colors.js"></script>
Lorem ipsum dolor sit amet, his id nonumy quaestio efficiantur. Quidam deleniti eum no, pri adhuc putant ea. Nec cu melius accusata, et vim lorem quaeque minimum. At aperiri principes complectitur eam, quo ne soleat accusamus ullamcorper, sed fugit adipiscing
no. Eripuit consequuntur quo no, his accusamus persequeris ea. Exerci delenit ad eos, ei sea tamquam ancillae necessitatibus. Est legere possim mnesarchum an. Vim nonumes expetendis ea, mei te mutat propriae platonem, per ut feugiat reprimique. Has deserunt
nominati liberavisse ut. Per cibo ubique omittam in, has te decore denique, justo nominavi id pro. Ei ius paulo deserunt pertinacia. Nec nostro expetenda id. Nec no esse interesset, id qui ferri errem. Qui possim ponderum platonem ea, nostro epicuri nam
in. Ei consul ubique conclusionemque eum, et alterum apeirian nam. Quem odio adipiscing has ei. Et has solum perfecto tincidunt, quo no indoctum prodesset. Pri ut tritani ceteros tractatos, in legere disputationi mea. Ne mel mutat graeci, mei eu doctus
appetere. Ius dicam imperdiet id, duo commune phaedrum ut, ut reque minim vis. Instructior signiferumque mea id. Nam ut vocibus recusabo consulatu. No mea postea mandamus prodesset, his hinc iusto in, no atqui consequat his. Discere sapientem id vel,
eam ea idque lucilius, ne eos labitur pericula. Ea dicat sonet nec, te pri libris putant eirmod, ancillae voluptatibus ut eam. Dicat commune necessitatibus nec cu, an enim purto menandri vel, eu ferri altera admodum duo.Lorem ipsum dolor sit amet, his
id nonumy quaestio efficiantur. Quidam deleniti eum no, pri adhuc putant ea. Nec cu melius accusata, et vim lorem quaeque minimum. At aperiri principes complectitur eam, quo ne soleat accusamus ullamcorper, sed fugit adipiscing no. Eripuit consequuntur
quo no, his accusamus persequeris ea. Exerci delenit ad eos, ei sea tamquam ancillae necessitatibus. Est legere possim mnesarchum an. Vim nonumes expetendis ea, mei te mutat propriae platonem, per ut feugiat reprimique. Has deserunt nominati liberavisse
ut. Per cibo ubique omittam in, has te decore denique, justo nominavi id pro. Ei ius paulo deserunt pertinacia. Nec nostro expetenda id. Nec no esse interesset, id qui ferri errem. Qui possim ponderum platonem ea, nostro epicuri nam in. Ei consul ubique
conclusionemque eum, et alterum apeirian nam. Quem odio adipiscing has ei. Et has solum perfecto tincidunt, quo no indoctum prodesset. Pri ut tritani ceteros tractatos, in legere disputationi mea. Ne mel mutat graeci, mei eu doctus appetere. Ius dicam
imperdiet id, duo commune phaedrum ut, ut reque minim vis. Instructior signiferumque mea id. Nam ut vocibus recusabo consulatu. No mea postea mandamus prodesset, his hinc iusto in, no atqui consequat his. Discere sapientem id vel, eam ea idque lucilius,
ne eos labitur pericula. Ea dicat sonet nec, te pri libris putant eirmod, ancillae voluptatibus ut eam. Dicat commune necessitatibus nec cu, an enim purto menandri vel, eu ferri altera admodum duo.
<div id="wrapper">
  <div id="hsv_map">
    <div id="colorDiskWrapper">
      <canvas id="surface" width="500" height="500"></canvas>
      <div id="cover"></div>
      <div id="hsv-cursor"></div>
    </div>
    <div id="luminenceBarWrapper">
      <div id="bar-bg"></div>
      <div id="bar-white"></div>
      <canvas id="luminanceBar" width="15" height="500"></canvas>
      <div id="hsv-barcursors" id="hsv_cursors">
        <div id="hsv-barcursor"></div>
      </div>
    </div>
  </div>
</div>

最佳答案

将此添加到您的 CSS 中:

html, body {
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    position: relative;
}

JSFIDDLE

关于javascript - 滚动时元素转到错误的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34756776/

有关javascript - 滚动时元素转到错误的位置的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  3. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  4. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  5. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  6. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  7. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  8. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  9. arrays - 这是 Ruby 中 Array.fill 方法的错误吗? - 2

    这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]

  10. ruby-on-rails - Ruby on Rails 计数器缓存错误 - 2

    尝试在我的RoR应用程序中实现计数器缓存列时出现错误Unknownkey(s):counter_cache。我在这个问题中实现了模型关联:Modelassociationquestion这是我的迁移:classAddVideoVotesCountToVideos0Video.reset_column_informationVideo.find(:all).eachdo|p|p.update_attributes:videos_votes_count,p.video_votes.lengthendenddefself.downremove_column:videos,:video_vot

随机推荐