什么';将SASS变量传递给javascript的行业标准方法是什么?
我环顾四周,看到了一个解决方案,在html中,有一个专门用于将sass变量传递给javascript的标记。我说的是第二个答案 我也尝试过使用html什么';将SASS变量传递给javascript的行业标准方法是什么?,javascript,html,sass,Javascript,Html,Sass,我环顾四周,看到了一个解决方案,在html中,有一个专门用于将sass变量传递给javascript的标记。我说的是第二个答案 我也尝试过使用html <div class="selector"></div> 但是看看开发工具中的dom,即使我们可以在呈现的页面上看到它,它也没有被添加,所以我不能用javascript来获取它 $('.selector').text() 每个人都是如何做到的?不确定“行业标准”,但这是一种非常方便的技术,也不太难。伪元素的内容不能通
<div class="selector"></div>
但是看看开发工具中的dom,即使我们可以在呈现的页面上看到它,它也没有被添加,所以我不能用javascript来获取它
$('.selector').text()
每个人都是如何做到的?不确定“行业标准”,但这是一种非常方便的技术,也不太难。伪元素的内容不能通过text()
获得,但必须使用getComputedStyle
使用body:after
的示例:
Sass(使用):
JavaScript:
if (window.getComputedStyle) {
var mq = window.getComputedStyle(document.body,':after').getPropertyValue('content');
}
if (mq.indexOf('small') !== -1) {
// do something
}
信用证:我第一次在这里看到这种技术:我认为通过CSS
内容
属性注入SASS变量是一种非常黑客的方法
相反,您可以将变量存储在单独的位置,并让SASS和JS读取它们
首先,将断点列表存储在breakpoints.json
文件中:
然后使用Ruby读取此JSON文件,并通过SASS函数将其内容作为SASS列表提供。将其放入指南针config.rb
:
在SASS代码中,读取如下断点:
$breakpoints: breakpoints()
在JS中,使用jQuery的.get
方法请求JSON文件,如下所示:
当我组装这个设置时,我发现了一个现有的解决方案,但我决定使用我最喜欢的SASS工具重新实现它:和
为了您的方便,我构建了一个概念验证,所有内容都设置得很好,其中包含一些丑陋的JS代码。:)
这里有一个 通过CSS
content
属性共享状态似乎脏了。我也不喜欢提出额外的XHR请求
我曾想过构建一个定制的解决方案,只需编译SASS文件和JS模块。但事实证明有一个名为npm的npm
包。正是这样。输出格式非常灵活,我很快就将其设置为Grunt.js
任务
$npm安装rosetta
下面是Gruntfile.js示例:
和package.json:
毕竟,您只需要在SASS中导入_shared_variables.scs,并在JavaScript中使用rosetta.js模块来访问公共变量。当您更改*.rose文件时,您的样式和JS将被更新。如果您使用的是
GULP
或GRUNT
(我希望您使用的是第一个)
此示例显示了如何使用gulp
:
在gulpfile或其他文件中定义颜色,然后将其导入gulpfile,然后可以动态构建SCSS
变量和javascript,如下所示:
变量_template.scss(不导入主scss文件)
app.js(包含colors变量的一些js文件)
gulpfile.js
SCSS变量的类似NPM gulp包:
libsass
,通常用作npm包(包装到JS中)。C的运行速度更快,但开发速度要慢得多,所以下一个官方实现将用Dart编写。几年后,另一个脚本kiddie会告诉你:“Wat?npm安装?你太不相关了,老头子!”getComputedStyle
会导致样式重新调整/并强制布局,这对性能非常不利,如果可能的话,最好避免它。@RayShan-如果你在页面呈现之前使用它,仍然很好,如果重新油漆,那就没什么意义了。不管怎么说,这都是关于您将读取CSS的代码放置在何处的时间安排。@vsync在呈现页面之前,如何运行getComputedStyle
?如果您在浏览器中的任何时候运行getComputedStyle
,都会影响性能。如果视图是数据驱动的,则数据应该位于单独的JSON文件中。SASS是在渲染之前编译的,因此可以在SPA页面中添加类似的内容。@RayShan-在SPA页面中,您可以在渲染任何内容之前运行任何javascript,因此您基本上有一个空白页面,因此重新绘制不是问题。这不是一个问题,除非它发生在一个很快的时间间隔(如w
if (window.getComputedStyle) {
var mq = window.getComputedStyle(document.body,':after').getPropertyValue('content');
}
if (mq.indexOf('small') !== -1) {
// do something
}
["0", "300px", "500px", "700px", "900px", "1100px"]
sass_options = { :custom => {'breakpoint_file' => 'breakpoints.json'} }
# This creates a SASS function debug() that returns $debug into SASS
module Sass::Script::Functions
def breakpoints
# Reading an array of breakpoints into a file
unless breakpoints_array_raw = JSON.load( IO.read( options[:custom]['breakpoint_file'] ))
raise Sass::SyntaxError.new("Error: Breakpoints file '#{options[:custom]['breakpoint_file']}' does not exist.")
end
# Converting strings in the array to SASS String literals
breakpoints_array_sassy = breakpoints_array_raw.map { |s| Sass::Script::String.new(s) }
# Returning the list into SASS
Sass::Script::List.new( breakpoints_array_sassy, :space )
end
end
$breakpoints: breakpoints()
var
breakpoints = [],
requestBreakpoints = $.get('breakpoints.json');
requestBreakpoints.done(function (response, textStatus, jqXHR){
breakpoints = response; // You might want to remove "px" here
});
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
css: {
files: ['sass/*.scss', 'sass/lib/*.scss', 'rosetta/*.rose'],
tasks: ['rosetta', 'compass']
}
},
compass: {
dist: {
options: {
sassDir: 'sass',
cssDir: '../static/css',
imagesDir: '../static/img',
javascriptsDir: '../static/js'
}
}
},
rosetta: {
default: {
src: ['rosetta/*.rose'],
options: {
jsFormat: 'requirejs',
cssFormat: 'scss',
jsOut: '../static/js/lib/rosetta.js',
cssOut: 'sass/_shared_variables.scss'
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('rosetta');
grunt.registerTask('default', ['watch']);
};
{
"name": "",
"version": "0.0.0",
"description": "",
"main": "Gruntfile.js",
"dependencies": {
"grunt": "^0.4.5",
"grunt-cli": "^0.1.13",
"grunt-contrib-compass": "^0.9.1",
"grunt-contrib-watch": "^0.6.1",
"rosetta": "git+https://github.com/ukolka/rosetta.git"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
...
$colors : ([COLORS])
...
var appColors = {[COLORS]};
var gulp = require('gulp'),
gutil = require('gulp-util'),
replace = require('gulp-replace');
var appColors = {
"red" : "#d63737",
"green" : "#69c962"
};
gulp.task('scssVars', ()=>{
var colorsString = JSON.stringify(appColors);
colorsString = colorsString.slice(2,colorsString.length - 2);
return gulp.src('css/variables_template.scss')
.pipe(replace(/[COLORS]/g, colorsString ))
.pipe(rename('variables.scss'))
.pipe(gulp.dest('/'))
});
// do more of less the same for your app.js, only without renaming, if possible