本文介绍了javascript createElement(),样式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我写了这个函数:

 function zoom(obj){
            var img = (!document.getElementById(obj))?false:document.getElementById(obj);
            var fullImage = (img.getAttribute("image") == null)?false:img.getAttribute("image");
            if(!fullImage || !img) { return false; }
            if(!document.getElementById("::img")) {
            var ob = "<div id='::img' style='position:absolute;top:300px;left:300px;width:200px;height:200px;-moz-border-radius:100px;border:1px solid #ddd;-moz-box-shadow: 0px 0px 8px #fff;display:none;'></div>";
            document.write(ob);}
            img.onmousemove = function(e) {
            var x = Math.floor(((e.pageX-7) - (img.offsetLeft - 8)) * 100 / img.width);
            var y = Math.floor(((e.pageY-7) - (img.offsetTop - 8)) * 100 / img.height);
            x = (x>100)?100:(x<0)?0:x;
            y = (y>100)?100:(y<0)?0:y;
            var ob = document.getElementById("::img");
            ob.style.background = "url('" + fullImage + "') no-repeat";
            ob.style.display = 'block';
            ob.style.backgroundPosition = x + '% ' + y + '%';
            ob.style.left = e.pageX + "px";
            ob.style.top = e.pageY + "px";
            }
            img.onmouseout = function() { document.getElementById("::img").style.display='none'; }
        }




  1. 我试图使用createElement ()和appendChild()函数而不是:

  1. I tried to use createElement() and appendChild() functions instead of this :

 var ob = `""`;
            document.write(ob);

但功能不起作用,如何使其工作createElement()。

but function does't work, how to make it to work with createElement().

是否可以使用纯色 JAVASCRIPT 添加一行代码:

is it possible to add all style with one line code with pure JAVASCRIPT :



ob.style.background = "url('" + fullImage + "') no-repeat";
                ob.style.display = 'block';
                ob.style.backgroundPosition = x + '% ' + y + '%';
                ob.style.left = e.pageX + "px";
                ob.style.top = e.pageY + "px";

预览:

Preview: JsFiddle

推荐答案

var obj = document.createElement('div');
obj.id = "::img";
obj.style.cssText = 'position:absolute;top:300px;left:300px;width:200px;height:200px;-moz-border-radius:100px;border:1px  solid #ddd;-moz-box-shadow: 0px 0px 8px  #fff;display:none;';

document.getElementById("divInsteadOfDocument.Write").appendChild(obj);

您还可以一次性查看如何设置CSS(使用 element.style.cssText )。

You can also see how to set the the CSS in one go (using element.style.cssText).

我建议你使用一些更有意义的变量名称和不要对不同的元素使用相同的名称。看起来你正在使用 obj 来表示不同的元素(覆盖函数中的值),这可能会令人困惑。

I suggest you use some more meaningful variable names and don't use the same name for different elements. It looks like you are using obj for different elements (overwriting the value in the function) and this can be confusing.

这篇关于javascript createElement(),样式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 22:49