我想要写一个浏览器(Chrome / FF)的扩展,需要来选择网页上的元素。我想它的行为类似于Firebug的元素检查员一样。您单击检查箭头,然后你可以悬停/突出的元素。当您单击所需的元素,该元素进行检查。我只是有兴趣的代码,允许用户选择一个元素 - 而不是在实际检查,或任何类似

由于我在写一个扩展,它可能是好的,如果你能提供非的jQuery /样机/等代码,所以我不必分发。

有帮助吗?

解决方案

我写此使用jQuery的实现作为另一个项目的组成部分。源和文档可在这里: https://github.com/andrewchilds/jQuery.DomOutline

其他提示

我最近需要这样的功能对于一个项目我工作的,原来,我不得不使用的侧面,以形成一个框,因为否则event.target当你把鼠标移动将最终被选择,如果我打算使用z-index: -1这将是一个位的的,当你有很多的元素重叠的...等。

下面是一个版本,我已经从我的项目的效益转换,它涉及到jQuery的,但它是非常简单的转换的香草的,因为只有从jQuery的的mousemovecss方法被使用。

分步说明。

首先创建的 5 需要的是HTML元素。

<div id="selector">
    <div id="selector-top"></div>
    <div id="selector-left"></div>
    <div id="selector-right"></div>
    <div id="selector-bottom"></div>
</div>

其次上创建一个mousemove事件document(或容器)

$(document).mousemove(function(event) { ... });

然后,mousemove内我们会做一些基本检查,以防止选择所述HTML, BODY, selector

var id = event.target.id, tagName = event.target.tagName;

if(id.indexOf('selector') !== -1 || tagName === 'BODY' || tagName === 'HTML') {
   return;
} 

然后,我们需要创建一个对象来存储我们元件像这样。

var elements = {
    top: $('#selector-top'),
    left: $('#selector-left'),
    right: $('#selector-right'),
    bottom: $('#selector-bottom')
};

这之后,我们存储一些变量持有关于像这样的目标元素的一些信息。

var $target = event.target;
    targetOffset = $target.getBoundingClientRect(),
    targetHeight = targetOffset.height,
    targetWidth  = targetOffset.width;

然后,所有我们是计算的位置&的高度作为所有的 4 像这样选择器的侧面。

elements.top.css({
    left:  (targetOffset.left - 4),
    top:   (targetOffset.top - 4),
    width: (targetWidth + 5)
});

elements.bottom.css({
    top:   (targetOffset.top + targetHeight + 1),
    left:  (targetOffset.left  - 3),
    width: (targetWidth + 4)
});

elements.left.css({
    left:   (targetOffset.left  - 5),
    top:    (targetOffset.top  - 4),
    height: (targetHeight + 8)
});

elements.right.css({
    left:   (targetOffset.left + targetWidth + 1),
    top:    (targetOffset.top  - 4),
    height: (targetHeight + 8)
});

+aFewPixels的所有只是一个小的优化使得有像在选择器和目标之间2px间隙。

对于CSS这是我想出了。

#selector-top, #selector-bottom {
    background: blue;
    height:3px;
    position: fixed;
    transition:all 300ms ease;
}

#selector-left, #selector-right {
    background: blue;
    width:3px;
    position: fixed;
    transition:all 300ms ease;
}

transition给出了选择一个非常好的滑动效果。

试试演示 http://jsfiddle.net/rFc8E/9/

  

请注意:这也适用于transform: scale(2);如。当一个元件被缩放的大小。

编辑:我刚刚更新了这个,我注意到elements对象是的事件处理程序,我已经搬到外面它在演示中,这是因为现在很重要的性能改进,elements对象只被创建的一次,而不是数十万如果没有数百万的时代mousemove事件中

一个简单的方法来做到这一点是使用一个轮廓,而不是一个边界:

.highlight { outline: 4px solid #07C; }

只需添加和删除类到要选择的任何元素/取消选择(下面代码未正确测试):

document.body.addEventListener("mouseover", function(e) {
    e.stopPropagation();
    e.target.addEventListener("mouseout", function (e) {
        e.target.className = e.target.className.replace(new RegExp(" highlight\\b", "g"), "");
    });
    e.target.className += " highlight";
});

由于正在使用的概要,(这是由镀铬的支持),而不是一个边界,元件不会跳周围。我用我的 EasyReader扩展类似的东西。

另外检查这一个:

http://rockingcode.com/tutorial /元件-DOM树-jQuery的插件 - 萤火样的功能/

我发现它非常有见地..而且这里有一个演示:

http://rockingcode.com/demos/elemtree/

希望这有助于。

HTML元素选取器(香草JS)

选择并强调任何HTML元素的网页上只有香草JS!在Chrome,FF,和Opera测试,不工作在IE中。结果

如何工作的:

你需要什么,其实很简单。你可以创建一个有JS背景的空div箱和移动它以突出徘徊元素之上。 这里的JS代码:

const hoverBox = document.createElement("div");
console.log("hoverBox: ", hoverBox);
hoverBox.style.position = "absolute";
// change to whatever highlight color you want
hoverBox.style.background = "rgba(153, 235, 255, 0.5)";
// avoid blocking the hovered element and its surroundings
hoverBox.style.zIndex = "0";
document.body.appendChild(hoverBox);
let previousTarget;
document.addEventListener("mousemove", (e) => {
    let target = e.target;
    if (target === hoverBox) {
        // the truely hovered element behind the added hover box
        const hoveredElement = document.elementsFromPoint(e.clientX, e.clientY)[1];
        if (previousTarget === hoveredElement){
            // avoid repeated calculation and rendering
            return;
        } else{
            target = hoveredElement;
        }
    } else{
        previousTarget = target;
    }
    const targetOffset = target.getBoundingClientRect();
    const targetHeight = targetOffset.height;
    const targetWidth = targetOffset.width;
    // add a border around hover box
    const boxBorder = 5;
    hoverBox.style.width = targetWidth + boxBorder * 2 + "px";
    hoverBox.style.height = targetHeight + boxBorder * 2 + "px";
    // need scrollX and scrollY to account for scrolling
    hoverBox.style.top = targetOffset.top + window.scrollY - boxBorder + "px";
    hoverBox.style.left = targetOffset.left + window.scrollX - boxBorder + "px";
});

查看演示结果 我也作了 NPM包获得与更多的用户配置像元件拾取器背景颜色,边框宽度,过渡等 这里的 GitHub的页面

有一个类似的问题问#1,它有很多很好的答案: 有谁知道一个DOM检查JavaScript库或者插件?

对于那些谁正在寻找一个快速和肮脏的溶液:

http://userscripts.org/scripts/review/3006 是最容易的。只要把<script></script>标签中的代码,你是好去。

https://github.com/josscrowcroft /Simple-JavaScript-DOM-Inspector/blob/master/inspector.js 是略好还是很容易集成英寸

有关更复杂的元素检查,你可能要检查出SelectorGadget由乌迪如指出。检查员选择的代码是在 http://www.selectorgadget.com/stable/lib/ interface.js

下面是用纯的JavaScript作为替代的库。

瞟着房间JS: https://github.com/hsynlms/theroomjs

// theroom information template for target element
var template="";
template += "<div id=\"theroom-info\">";
template += "  <span id=\"theroom-tag\"><\/span>";
template += "  <span id=\"theroom-id\"><\/span>";
template += "  <span id=\"theroom-class\"><\/span>";
template += "<\/div>";
template += "";
template += "<style>";
template += "  #theroom-info {";
template += "    position: fixed;";
template += "    bottom: 0;";
template += "    width: 100%;";
template += "    left: 0;";
template += "    font-family: \"Courier\";";
template += "    background-color: #ffffff;";
template += "    padding: 10px;";
template += "    color: #333333;";
template += "    text-align: center;";
template += "    box-shadow: 0px 4px 20px rgba(0,0,0,0.3);";
template += "  }";
template += "";
template += "  #theroom-tag {";
template += "    color: #C2185B;";
template += "  }";
template += "";
template += "  #theroom-id {";
template += "    color: #5D4037;";
template += "  }";
template += "";
template += "  #theroom-class {";
template += "    color: #607D8B;";
template += "  }";
template += "<\/style>";

var options = {
  template: template,
  showInfo: true
};

// initialize
theRoom.start(options);

codepen演示

您需要做的是创造高亮4个元素。他们将形成一个空方,等你的鼠标活动都是免费的火灾。这是类似于此覆盖例如我做了。

不同的是,只需要四个元件(没有调整大小标记物),并且的4个框的大小和位置是有点不同(模拟天生到红色边框)。然后你就可以在你的事件处理程序使用event.target,因为它在默认情况下得到真正的最顶端的元素。

<强>另一种方法是隐藏关节外元件,得到elementFromPoint,计算再装回。

他们比光更快,我可以告诉你。甚至爱因斯坦会同意:)

<强> 1)elementFromPoint叠加/边界 - [ demo1的] < EM> FF需要3.0 +

var box = $("<div class='outer' />").css({
  display: "none", position: "absolute", 
  zIndex: 65000, background:"rgba(255, 0, 0, .3)"
}).appendTo("body");

var mouseX, mouseY, target, lastTarget;

// in case you need to support older browsers use a requestAnimationFrame polyfill
// e.g: https://gist.github.com/paulirish/1579671
window.requestAnimationFrame(function frame() {
  window.requestAnimationFrame(frame);
    if (target && target.className === "outer") {
        box.hide();
        target = document.elementFromPoint(mouseX, mouseY);
    }
    box.show();   

    if (target === lastTarget) return;

    lastTarget = target;
    var $target = $(target);
    var offset = $target.offset();
    box.css({
        width:  $target.outerWidth()  - 1, 
        height: $target.outerHeight() - 1, 
        left:   offset.left, 
        top:    offset.top 
    });
});

$("body").mousemove(function (e) {
    mouseX = e.clientX;
    mouseY = e.clientY;
    target = e.target;
});

<强> 2)鼠标悬停边界 - [ DEMO2 ]

var box = new Overlay();

$("body").mouseover(function(e){
  var el = $(e.target);
  var offset = el.offset();
  box.render(el.outerWidth(), el.outerHeight(), offset.left, offset.top);
});​

/**
 * This object encapsulates the elements and actions of the overlay.
 */
function Overlay(width, height, left, top) {

    this.width = this.height = this.left = this.top = 0;

    // outer parent
    var outer = $("<div class='outer' />").appendTo("body");

    // red lines (boxes)
    var topbox    = $("<div />").css("height", 1).appendTo(outer);
    var bottombox = $("<div />").css("height", 1).appendTo(outer);  
    var leftbox   = $("<div />").css("width",  1).appendTo(outer);
    var rightbox  = $("<div />").css("width",  1).appendTo(outer);

    // don't count it as a real element
    outer.mouseover(function(){ 
        outer.hide(); 
    });    

    /**
     * Public interface
     */

    this.resize = function resize(width, height, left, top) {
      if (width != null)
        this.width = width;
      if (height != null)
        this.height = height;
      if (left != null)
        this.left = left;
      if (top != null)
        this.top = top;      
    };

    this.show = function show() {
       outer.show();
    };

    this.hide = function hide() {
       outer.hide();
    };     

    this.render = function render(width, height, left, top) {

        this.resize(width, height, left, top);

        topbox.css({
          top:   this.top,
          left:  this.left,
          width: this.width
        });
        bottombox.css({
          top:   this.top + this.height - 1,
          left:  this.left,
          width: this.width
        });
        leftbox.css({
          top:    this.top, 
          left:   this.left, 
          height: this.height
        });
        rightbox.css({
          top:    this.top, 
          left:   this.left + this.width - 1, 
          height: this.height  
        });

        this.show();
    };      

    // initial rendering [optional]
    // this.render(width, height, left, top);
}

一个非常基本的实施可以很容易地使用.onmouseovere.target完成而无需jQuery的:

var last,
    bgc;
document.onmouseover = function(e) {
    var elem = e.target;

    if (last != elem) {
        if (last != null) {
            last.classList.remove("hovered");
        }

        last = elem;
        elem.classList.add("hovered");
    }
}

使用,如果你想给孩子换背景以及下面的CSS:

.hovered,
.hovered * {
    cursor: pointer;
    color: black;
    background-color: red;
}

演示


如果您要选择只在边缘附近的元素(或选择边缘附近的家长和元素本身其他地方),你可以使用.getBoundingClientRect

var last;
window.addEventListener("mousemove", function(e) {
  if(last) {
    last.style.background = ''; // empty is enough to restore previous value
  }
    var elem = e.target;

  if(elem === document.body || elem === document.documentElement) {
    return;
  }
  var bb = elem.getBoundingClientRect();
  var xr = e.pageX - bb.left; // x relative to elem
  var yr = e.pageY - bb.top; // y relative to elem
  var ew = 10; // edge width

  if(
       xr <= ew
    || xr >= bb.width - ew
    || yr <= ew
    || yr >= bb.height - ew
  ){
    elem.style.background = 'red';
    last = elem;
  }
});

一些边界配对,这可以是用于选择相当可用。 演示

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top