2012-12-08 18 views
0

google-font-Api와 작동하는 선택 메뉴를 만들었습니다. 나는 JSBIN에서 함수를 만들었다. 내 작업은 http://jsbin.com/ocutuk/18/내 페이지에서 함수 호출이 작동하지 않습니다.

이다.하지만 html 페이지에서 코드의 사본을 만들 때 페이지에 글꼴 이름을 적재하지도 않는다. 나는 그것을 작동하게 만들려고 노력했다. 그러나 그것은 아직도 막 다른 골목에있다. 이것은 내 html 코드입니다

<!DOCTYPE html> 
<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script> 
    <meta charset=utf-8 /> 
    <title>FONT API</title> 
    <script> 
    function SetFonts(fonts) { 
    for (var i = 0; i < fonts.items.length; i++) {  
    $('#styleFont') 
    .append($("<option></option>") 
    .attr("value", fonts.items[i].family) 
    .text(fonts.items[i].family)); 
    }  
    } 

    var script = document.createElement('script'); 
    script.src = 'https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyB8Ua6XIfe-gqbkE8P3XL4spd0x8Ft7eWo&callback=SetFonts'; 
    document.body.appendChild(script); 


    WebFontConfig = { 
google: { families: ['ABeeZee', 'Abel', 'Abril Fatface', 'Aclonica', 'Acme', 'Actor', 'Adamina', 'Advent Pro', 'Aguafina Script', 'Akronim', 'Aladin', 'Aldrich', 'Alegreya', 'Alegreya SC', 'Alex Brush', 'Alfa Slab One', 'Alice', 'Alike', 'Alike Angular', 'Allan', 'Allerta', 'Allerta Stencil', 'Allura', 'Almendra', 'Almendra Display', 'Almendra SC', 'Amarante', 'Amaranth', 'Amatic SC', 'Amethysta', 'Anaheim', 'Andada', 'Andika', 'Angkor', 'Annie Use Your Telescope', 'Anonymous Pro', 'Antic', 'Antic Didone', 'Antic Slab', 'Anton', 'Arapey', 'Arbutus', 'Arbutus Slab', 'Architects Daughter', 'Archivo Black', 'Archivo Narrow', 'Arimo', 'Arizonia', 'Armata', 'Artifika', 'Arvo', 'Asap', 'Asset', 'Astloch', 'Asul', 'Atomic Age', 'Aubrey', 'Audiowide', 'Autour One', 'Average', 'Average Sans', 'Averia Gruesa Libre', 'Averia Libre', 'Averia Sans Libre', 'Averia Serif Libre', 'Bad Script', 'Balthazar', 'Bangers', 'Basic', 'Battambang', 'Baumans', 'Bayon', 'Belgrano', 'Belleza', 'BenchNine', 'Bentham', 'Berkshire Swash', 'Bevan', 'Bigelow Rules', 'Bigshot One', 'Bilbo', 'Bilbo Swash Caps', 'Bitter', 'Black Ops One', 'Bokor', 'Bonbon', 'Boogaloo', 'Bowlby One', 'Bowlby One SC', 'Brawler', 'Bree Serif', 'Bubblegum Sans', 'Bubbler One', 'Buda', 'Buenard', 'Butcherman', 'Butterfly Kids', 'Cabin', 'Cabin Condensed', 'Cabin Sketch', 'Caesar Dressing', 'Cagliostro', 'Calligraffitti', 'Cambo', 'Candal', 'Cantarell', 'Cantata One', 'Cantora One', 'Capriola', 'Cardo', 'Carme', 'Carrois Gothic', 'Carrois Gothic SC', 'Carter One', 'Caudex', 'Cedarville Cursive', 'Ceviche One', 'Changa One', 'Chango', 'Chau Philomene One', 'Chela One', 'Chelsea Market', 'Chenla', 'Cherry Cream Soda', 'Cherry Swash', 'Chewy', 'Chicle', 'Chivo', 'Cinzel', 'Cinzel Decorative', 'Clicker Script', 'Coda', 'Coda Caption', 'Codystar', 'Combo', 'Comfortaa', 'Coming Soon', 'Concert One', 'Condiment', 'Content', 'Contrail One', 'Convergence', 'Cookie', 'Copse', 'Corben', 'Courgette', 'Cousine', 'Coustard', 'Covered By Your Grace', 'Crafty Girls', 'Creepster', 'Crete Round', 'Crimson Text', 'Croissant One', 'Crushed', 'Cuprum', 'Cutive', 'Cutive Mono']} 
}; 
(function() { 
var wf = document.createElement('script'); 
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + 
    '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; 
wf.type = 'text/javascript'; 
wf.async = 'true'; 
var s = document.getElementsByTagName('script')[0]; 
s.parentNode.insertBefore(wf, s); 
})(); 


$("#styleFont").change(function(){ 
    var id =$('#styleFont option' +':selected').val(); 
          $("#custom_text").css('font-family',id); 

    }); 


    </script> 
    <style> 
     #custom_text { 
    font-family: Arial; 
    resize: none; 
    margin-top: 20px; 
    width: 500px; 
    } 
     #styleFont { 
    width: 100px; 
    } 
    </style> 

    </head> 
    <body> 
    <select id="styleFont"> 
    </select><br> 
    <textarea id="custom_text"></textarea> 
    </body> 
    </html> 

어떻게 작동시킬 수 있습니까? 내가 여기서 만들고있는 실수는 뭐지?

+0

그것은 JS 빈에서 잘 작동합니다. 무슨 문제인가? –

+0

내가 html 페이지에 이것을 추가 할 때 거기에서 작동하지 않는다. –

+0

온라인 어딘가에 출판 했니? 어쩌면 다른 JS 파일에 충돌이있을 수 있습니까? –

답변

2

스크립트를 페이지 맨 아래로 이동하십시오. 현재 문제는 DOM이 형성되기 전에 스크립트가 실행되고 있다는 것입니다.

<!DOCTYPE html> 
<html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script> 
    <meta charset=utf-8 /> 
    <title>FONT API</title> 

    <style> 
     #custom_text { 
    font-family: Arial; 
    resize: none; 
    margin-top: 20px; 
    width: 500px; 
    } 
     #styleFont { 
    width: 100px; 
    } 
    </style> 

    </head> 
    <body> 
    <select id="styleFont"> 
    </select><br> 
    <textarea id="custom_text"></textarea> 

    <script> 
    function SetFonts(fonts) { 
    for (var i = 0; i < fonts.items.length; i++) {  
    $('#styleFont') 
    .append($("<option></option>") 
    .attr("value", fonts.items[i].family) 
    .text(fonts.items[i].family)); 
    }  
    } 

    var script = document.createElement('script'); 
    script.src = 'https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyB8Ua6XIfe-gqbkE8P3XL4spd0x8Ft7eWo&callback=SetFonts'; 
    document.body.appendChild(script); 


    WebFontConfig = { 
google: { families: ['ABeeZee', 'Abel', 'Abril Fatface', 'Aclonica', 'Acme', 'Actor', 'Adamina', 'Advent Pro', 'Aguafina Script', 'Akronim', 'Aladin', 'Aldrich', 'Alegreya', 'Alegreya SC', 'Alex Brush', 'Alfa Slab One', 'Alice', 'Alike', 'Alike Angular', 'Allan', 'Allerta', 'Allerta Stencil', 'Allura', 'Almendra', 'Almendra Display', 'Almendra SC', 'Amarante', 'Amaranth', 'Amatic SC', 'Amethysta', 'Anaheim', 'Andada', 'Andika', 'Angkor', 'Annie Use Your Telescope', 'Anonymous Pro', 'Antic', 'Antic Didone', 'Antic Slab', 'Anton', 'Arapey', 'Arbutus', 'Arbutus Slab', 'Architects Daughter', 'Archivo Black', 'Archivo Narrow', 'Arimo', 'Arizonia', 'Armata', 'Artifika', 'Arvo', 'Asap', 'Asset', 'Astloch', 'Asul', 'Atomic Age', 'Aubrey', 'Audiowide', 'Autour One', 'Average', 'Average Sans', 'Averia Gruesa Libre', 'Averia Libre', 'Averia Sans Libre', 'Averia Serif Libre', 'Bad Script', 'Balthazar', 'Bangers', 'Basic', 'Battambang', 'Baumans', 'Bayon', 'Belgrano', 'Belleza', 'BenchNine', 'Bentham', 'Berkshire Swash', 'Bevan', 'Bigelow Rules', 'Bigshot One', 'Bilbo', 'Bilbo Swash Caps', 'Bitter', 'Black Ops One', 'Bokor', 'Bonbon', 'Boogaloo', 'Bowlby One', 'Bowlby One SC', 'Brawler', 'Bree Serif', 'Bubblegum Sans', 'Bubbler One', 'Buda', 'Buenard', 'Butcherman', 'Butterfly Kids', 'Cabin', 'Cabin Condensed', 'Cabin Sketch', 'Caesar Dressing', 'Cagliostro', 'Calligraffitti', 'Cambo', 'Candal', 'Cantarell', 'Cantata One', 'Cantora One', 'Capriola', 'Cardo', 'Carme', 'Carrois Gothic', 'Carrois Gothic SC', 'Carter One', 'Caudex', 'Cedarville Cursive', 'Ceviche One', 'Changa One', 'Chango', 'Chau Philomene One', 'Chela One', 'Chelsea Market', 'Chenla', 'Cherry Cream Soda', 'Cherry Swash', 'Chewy', 'Chicle', 'Chivo', 'Cinzel', 'Cinzel Decorative', 'Clicker Script', 'Coda', 'Coda Caption', 'Codystar', 'Combo', 'Comfortaa', 'Coming Soon', 'Concert One', 'Condiment', 'Content', 'Contrail One', 'Convergence', 'Cookie', 'Copse', 'Corben', 'Courgette', 'Cousine', 'Coustard', 'Covered By Your Grace', 'Crafty Girls', 'Creepster', 'Crete Round', 'Crimson Text', 'Croissant One', 'Crushed', 'Cuprum', 'Cutive', 'Cutive Mono']} 
}; 
(function() { 
var wf = document.createElement('script'); 
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + 
    '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; 
wf.type = 'text/javascript'; 
wf.async = 'true'; 
var s = document.getElementsByTagName('script')[0]; 
s.parentNode.insertBefore(wf, s); 
})(); 


$("#styleFont").change(function(){ 
    var id =$('#styleFont option' +':selected').val(); 
          $("#custom_text").css('font-family',id); 

    }); 


    </script> 
    </body> 
    </html> 
+0

+1 감사합니다. –

+0

+1. 가능한 해결책. 더 나은 접근법은 모든 코드를 "준비된"핸들러 ('$ (function() {/ * 모든 초기화 스크립트 * /});)로 사용하거나 적절한 시간에 코드를 실행하기 위해 requireJS와 같은 일부 AMD 프레임 워크를 사용하는 것입니다. –

+0

@ThomasHigginbotham WebFontConfig = { google : {families : [ 'ABeeZee', 'Abel'....]}에있는 모든 글꼴 모음을로드하려고했습니다. }}; 하지만 그 중 일부만로드하는 방법은 모두로드하는 것입니다 –

0

글쎄, 이유는 간단하다 :

당신은 완전히로드지기 전에 약간의 DOM 요소를 조작하기 위해 노력했다.

문제를 해결할 것

$(function(){ 
} 

내부 코드를 배치.

은보다 구체적으로는, 당신이 좋아하는 코드를 변경할 수 있습니다

function SetFonts(fonts) { 
    for (var i = 0; i < fonts.items.length; i++) { 
    $('#styleFont') 
    .append($("<option></option>") 
    .attr("value", fonts.items[i].family) 
    .text(fonts.items[i].family)); 
    } 
} 

$(function(){ 
var script = document.createElement('script'); 
script.src = 'https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyB8Ua6XIfe-gqbkE8P3XL4spd0x8Ft7eWo&callback=SetFonts'; 
document.body.appendChild(script); 

// all the rest of your code.... 
}); 
+0

나는 이것을 시도했지만 작동하지 않았다. –

+0

$ (function() {...}) 안에 SetFonts 함수를 포함시키는 실수를했다. –

관련 문제