使用鼠标坐标作为javascript函数的像素值

时间:2013-10-15 08:36:10

标签: javascript height mouse-coordinates

有没有办法输入鼠标点击坐标作为更改元素属性的数量,如下面的函数类型?具体来说有没有办法使用鼠标点击的Y坐标作为高度的像素数量而不是固定的像素数?

function changeObject() {
    document.getElementById('object').style.height = '500px';
}

编辑:

使用cookies记住以前的身高

<script type="text/javascript">
function setCookie (name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}
function getCookie (name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset);
            if (end == -1) {
                end = cookie.length;
            }
            setStr = unescape(cookie.substring(offset, end));
        }
    }
    if (setStr == 'false') {
        setStr = false;
    } 
    if (setStr == 'true') {
        setStr = true;
    }
    if (setStr == 'null') {
        setStr = null;
    }
    return(setStr);
}
  document.getElementById('bookmarktag').onclick = function(event){
    var clickX = event.clientX + document.body.scrollLeft;
      var clickY = event.clientY + document.body.scrollTop; 

    document.getElementById('bookmark').style.height = clickY + 'px';
    document.getElementById('bookmark2').style.marginTop = clickY + 'px';

    document.getElementById('bookmarkdiv2').style.display = 'block';
    document.getElementById('bookmarkdiv').style.display = 'none';

    setCookie('bookmark_state', true);
}  

function checkBookmark() {
    if (getCookie('bookmark_state') == null) {
        document.getElementById('bookmarkdiv').style.display = 'block';
    }   
    if (getCookie('bookmark_state') == true) {
            document.getElementById('bookmark').style.height = clickY + 'px';
            document.getElementById('bookmark2').style.marginTop = clickY + 'px';

            document.getElementById('bookmarkdiv2').style.display = 'block';
            document.getElementById('bookmarkdiv').style.display = 'none';
    }  
}
</script>

1 个答案:

答案 0 :(得分:0)

尝试相对于文档

document.getElementById('someElement').onclick = function(event){
    var clickX = event.clientX + document.body.scrollLeft;
    var clickY = event.clientY + document.body.scrollTop;

    document.getElementById('object').style.height = clickY + 'px';
}