如何检查页面中的位置?

时间:2012-06-14 17:24:20

标签: javascript html greasemonkey userscripts

我使用类似的东西按条件点击页面上的元素:

var findElem = function(elems, text) {
    for (var i = 0; i < elems.length; i++) {
        if (elems[i].textContent == text) {
            return elems[i];
        } else {
            var result = findElem(elems[i].children, text);
            if (result != undefined) {
                return result;
            }
        }
    }
    return;
}

switch (document.getElementById('my_id').value) {
    case "1":
        findElem(document.documentElement.children, "blabla1").click();
        break;
    case "2":
        findElem(document.documentElement.children, "blabla2").click();
        break;
    default:
        break;
}

我想在此代码中再添加一个条件。

我工作的页面是这样的:

<body id="something">

<div id="something2" class="container">
    <div id="header">
        <a class="hmm" href="somelink"></a>
        <a class="aname" target="_blank" href="anotherlink"></a>
    </div>

    <div id="anotherthing" class="anotherthing2">

<div class="differentthing " style="left: 2px; ">
    <div class="asdafad"></div>
</div>

我必须查看differentthing是否没有style

总之,我想做这样的事情:

switch (document.getElementById('my_id').value) {
    case "1":
        ---if differentthing has no style attrib then---
        findElem(document.documentElement.children, "blabla1").click();
        break;

所以,如果页面的differentthing部分是这样的

<div class="differentthing ">

然后做findElem.click事。

如果它是<div class="differentthing " style="left: 2px; ">则不做任何事情。

我希望我能描述一下。我怎样才能做到这一点?抱歉我的英语不好。

3 个答案:

答案 0 :(得分:2)

switch (document.getElementById('my_id').value) {
    case "1":
        // getting an array of elements with "differentthing" class
        var elements = document.getElementsByClassName("differentthing");

        // if there is just one and it does not have "style" attribute
        if (elements.length == 1 && !elements[0].getAttribute("style")){
            // perform some action
            findElem(document.documentElement.children, "blabla1").click();
        }        
        break;

答案 1 :(得分:0)

想看一个元素是否没有样式?

对于初学者,请使用jquery

var hasStyle = $(".differentthing").attr("style")
if(hasStyle){/*...do your cool stuff...*/}

attr方法设置或返回元素的属性。对你而言,它是风格属性。

答案 2 :(得分:0)

我认为您可以使用此函数来获取属性,在本例中为样式

http://www.w3schools.com/dom/met_element_getattribute.asp

<!DOCTYPE html>
<html>
   <head>
   </head>
<body>
   <p id="title" style="color:red">algo</p>

</body>
<script type="text/javascript">
  var prueba = document.getElementById('title').getAttribute('style');
  document.write(prueba);
</script>
</html>

另一个例子:

 switch (document.getElementById('my_id').value) {
   case "1":
    elements = document.getElementsByClassName('differentthing');
    for(x in elements){
       if(!x.getAttribute('style')){
           //dont have style attribute do something 
       }
    }
    findElem(document.documentElement.children, "blabla1").click();
    break;