我有一个DIV
当我点击它时会触发一个javascript点击文件上传按钮display:none
。它可以在我的电脑上使用Chrome,Firefox,Chromium。但我想知道为什么它不适用于我的朋友电脑。
是因为浏览器问题还是什么?我和我的朋友一起使用 不同版本的Ubuntu。点击DIV时没有任何事情发生。
这是我的代码
<div onclick='uploadphoto()' title='Click to edit Profile Picture'></div>
<form action="js/ajaxuploadprofile.php" method="post" name="sleeker" id="sleeker" enctype="multipart/form-data" style='display:none'>
<input type="hidden" name="maxSize" value="2000000" />
<input type="hidden" name="maxW" value="700" />
<input type="hidden" name="fullPath" value="images/profilepic/" />
<input type="hidden" name="relPath" value="../images/profilepic/" />
<input type="hidden" name="colorR" value="255" />
<input type="hidden" name="colorG" value="255" />
<input type="hidden" name="colorB" value="255" />
<input type="hidden" name="maxH" value="700" />
<input type="hidden" name="filename" value="filename" />
<input type="file" id='filename' name="filename" onchange="ajaxUpload(this.form,'js/ajaxuploadprofile.php?filename=name&maxSize=2000000&maxW=700&fullPath=images/profilepic/&relPath=../images/profilepic/&colorR=255&colorG=255&colorB=255&maxH=700','upload_area','File Uploading Please Wait...<br /><img src=\'images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' />','<img src=\'images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /> Error in Upload, check settings and path info in source code.'); return false;" />
</form>
<script type='text/javascript'>
function uploadphoto()
{
el = document.getElementById('filename');
if (el.onclick)
{
el.onclick();
}
else if (el.click)
{
el.click();
}
//$('#filename').click(); // <-- this also works for me but not my friend
//document.getElementById('filename').click(); // <-- same
}
</script>
更新了解决方案
最近我发现style='display:none'
会在某些浏览器中出现问题(或者可能是由于浏览器的版本)。对于我的情况,Chrome的版本在我和我的朋友之间是不同的,因此它可以在我的电脑上工作,但不是我朋友的电脑。但是,我可以将style='display:none'
替换为style='visibility:hidden;height:0px'
来解决此问题。现在代码在任何电脑上运行良好。
visibility:hidden
只是隐藏内容的视图,它仍然会占用一些空间。因此,我添加了height:0px
,以便它具有与display:none
相同的效果。
答案 0 :(得分:4)
这可能是浏览器问题。举个例子,它可能会导致IE出现问题。如果您使用的是jQuery,可以执行以下操作:
$('#button').trigger('click');
否则你可以尝试如下:
if( document.createEvent ) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
document.getElementById('button').dispatchEvent(evt);
} else if( document.createEventObject ) { // For IE 8 and below
var evObj = document.createEventObject();
document.getElementById('button').fireEvent('onclick', evObj);
}
答案 1 :(得分:1)
根据this article,您可以使用以下内容创建getElementById
版本,该版本即使在非常旧的浏览器中也能正常运行:
function getElement (id)
{
if (document.getElementById)
{
return document.getElementById(id);
}
else if (document.all)
{
return window.document.all[id];
}
else if (document.layers)
{
return window.document.layers[id];
}
}