javascriptを使用せずにリンクを(タブではなく)新しいブラウザウィンドウで開く方法はありますか?
4 に答える
これにより、タブではなく(JavaScriptを使用しますが、非常に簡潔に)新しいウィンドウが開きます。
<a href="print.html"
onclick="window.open('print.html',
'newwindow',
'width=300,height=250');
return false;"
>Print</a>
純粋なHTMLでは、これに影響を与えることはできません。過去に多くの誤用があったため、すべての最新のブラウザー(=ユーザー)がこの動作を完全に制御できます...
HTMLオプション
新しいウィンドウ(HTML4)または新しいブラウジングコンテキスト(HTML5)を開くことができます。最新のブラウザでのコンテキストの閲覧は、ほとんどが「新しいウィンドウ」ではなく「新しいタブ」です。それに影響を与えることはなく、最新のブラウザに新しいウィンドウを開くように「強制」することはできません。
これを行うには、アンカー要素の属性target
[1]を使用します。探している値は_blank
[2]です。
<a href="www.example.com/example.html" target="_blank">link text</a>
JavaScriptオプション
新しいウィンドウを強制することはjavascriptを介して可能です-javascriptソリューションについては以下のIevgenの優れた答えを参照してください。
(!)ただし、javascriptを介してウィンドウを開くと(アンカー要素からのonclickイベントで行われない場合)、ポップアップブロッカーによってブロックされる可能性があることに注意してください。
[1]この属性は、ブラウザにタブがなく、フレームセットの使用が最先端であった時代にまでさかのぼります。その間に、この属性の機能はわずかに変更されました(MDN Docuを参照) 。
[2]、、またはのよう_parent
に、 (フレームセットを念頭に置いて設計されているため)もはや意味をなさない値が他にもいくつかあります。_self
_top
私はその少し古いQを知っていますが、解決策を検索してここに到達した場合、jqueryを介して素晴らしいものを取得しました
jQuery('a[target^="_new"]').click(function() {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
});
<a target="_new">
すべてが新しいウィンドウで開きます
編集:
1つ目は、元のコードに少し変更を加えたところ、新しいウィンドウが開き、ユーザーの画面比率に完全に準拠しました(横向きのデスクトップの場合)
ただし、モバイルの場合は、新しいタブでリンクを開く次のコードを使用することをお勧めします(他の質問のzvonaの回答に感謝します)。
jQuery('a[target^="_new"]').click(function() {
return openWindow(this.href);
}
function openWindow(url) {
if (window.innerWidth <= 640) {
// if width is smaller then 640px, create a temporary a elm that will open the link in new tab
var a = document.createElement('a');
a.setAttribute("href", url);
a.setAttribute("target", "_blank");
var dispatch = document.createEvent("HTMLEvents");
dispatch.initEvent("click", true, true);
a.dispatchEvent(dispatch);
}
else {
var width = window.innerWidth * 0.66 ;
// define the height in
var height = width * window.innerHeight / window.innerWidth ;
// Ratio the hight to the width as the user screen ratio
window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
}
return false;
}
あなたはこれを試すことができます:-
<a href="some.htm" target="_blank">Link Text</a>
そして、これも試すことができます:-
<a href="some.htm" onclick="if(!event.ctrlKey&&!window.opera){alert('Hold the Ctrl Key');return false;}else{return true;}" target="_blank">Link Text</a>