console.log没有解析css样式

时间:2017-10-10 18:05:42

标签: javascript css console.log

我想在console.log中以彩虹色数组显示文本。问题是控制台似乎没有解析样式。相反,当我在控制台中尝试rainbowify(myString);时,它会输出文字字符串。我已经尝试了toString()但没有工作。

奇怪的是,如果我复制并粘贴输出并将其放入控制台日志(在控制台中),它可以正常工作。我需要理解为什么它不解析css样式,而只是将它作为字符串输出。



var myString = "abcdefghijklmnopqrstuvwxyz";
var rainbow = ["red", "yellow", "pink", "green", "purple", "orange", "blue"];

function rainbowify(string) {
  var splitString = string.split("");
  var stringConCat = "";
  var stringCss = "";
  for (var i = 0, j = 0; i < splitString.length; i++, j++) {
    stringConCat += "\"%c" + splitString[i] + "\"" + " + ";
    stringCss += "\"color : " + rainbow[j] + "\"" + ", ";
    if (j === rainbow.length - 1) {
      j = 0;
    }
  }
  var stringSliced = stringConCat.slice(0, -3);
  var cssSliced = stringCss.slice(0, -2);
  console.log(stringSliced + ", " + cssSliced);
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

您正在生成包含一堆JavaScript的字符串。将该字符串复制并粘贴到控制台(不带引号)时,将评估JavaScript。将该字符串直接传递给public class FeedHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { public static final String SEEK_BAR_PROGRESS_BUNDLE = "bundle_seek_bar_progress"; public static final String ACTION_ICON_BUNDLE = "bundle_icon"; public static final String RESET_AUDIO = "bundle_reset_audio"; private static final int MINE_BG_COLOR = R.color.feed_mine_bg; private static final int MINE_TEXT_COLOR = R.color.feed_mine_text; private static final int MINE_PLAY_ICON = R.drawable.ic_play_white_24dp; private static final int MINE_FILE_ICON = R.drawable.ic_file_white_18dp; private static final int THEIR_BG_COLOR = R.color.feed_others_bg; private static final int THEIR_TEXT_COLOR = R.color.feed_others_text; private static final int THEIR_PLAY_ICON = R.drawable.ic_play_black_24dp; private static final int THEIR_FILE_ICON = R.drawable.ic_file_black_18dp; private final SimpleDraweeView mAvatar; private final TextView mCreator; private final TextView mDate; private final CardView mCardView; private final TextView mText; private final TextView mLike; private final FeedHolderListener mListener; private final SimpleDraweeView mPicture; private final int mSize; private final View mAudioLayout; private final ImageButton mAudioAction; private final SeekBar mAudioBar; private final TextView mAudioLength; public FeedHolder(@NonNull final View itemView, final FeedHolderListener listener, final int size) { super(itemView); mAvatar = (SimpleDraweeView) itemView.findViewById(R.id.avatar); mCreator = (TextView) itemView.findViewById(R.id.creator); mDate = (TextView) itemView.findViewById(R.id.date); mCardView = (CardView) itemView.findViewById(R.id.card); mCardView.setOnLongClickListener(this); mCardView.setOnClickListener(this); mText = (TextView) itemView.findViewById(R.id.text); mLike = (TextView) itemView.findViewById(R.id.like); mPicture = (SimpleDraweeView) itemView.findViewById(R.id.picture); mLike.setOnClickListener(this); mAudioLayout = itemView.findViewById(R.id.audioLayout); mAudioAction = (ImageButton) itemView.findViewById(R.id.audioAction); mAudioBar = (SeekBar) itemView.findViewById(R.id.audioBar); mAudioLength = (TextView) itemView.findViewById(R.id.length); mAudioAction.setOnClickListener(this); itemView.setOnLongClickListener(this); mPicture.setOnLongClickListener(this); mPicture.setOnClickListener(this); mListener = listener; mSize = size; } @Override public void onClick(final View v) { int id = v.getId(); if (id == R.id.like) { v.setEnabled(false); v.postDelayed(new Runnable() { @Override public void run() { v.setEnabled(true); } }, 1000); if (mListener != null) { mListener.toggleLike(getAdapterPosition()); } }else if(id == R.id.audioAction) { if (mListener != null) { mAudioAction.setImageResource(mListener.onAudioActionClicked(getAdapterPosition(), mAudioBar.getProgress())); } }else { if (mListener != null) { mListener.onClick(getAdapterPosition()); } } } @Override public boolean onLongClick(View v) { if (mListener != null) { mListener.onLongClick(getAdapterPosition(), v); return true; }else { return false; } } public void onBind(@NonNull Feed feed, @NonNull final String userId, final int avatarSize){ setCreatedBy(feed.getCreatedBy(), avatarSize); setCreatedAt(feed.getCreatedAt()); setLiked(feed.isLiked(userId)); setLikedCount(feed.getLikedCount()); boolean mine = feed.getCreatedById().equals(userId); setColors(mine); switch (feed.getFeedType()) { case FEED_COMMENT: setText(feed.getShowingText()); mPicture.setVisibility(View.GONE); mAudioLayout.setVisibility(View.GONE); break; case FEED_IMAGE: setText(feed.getCaption()); setPicture(feed.getUrl(), feed.getPath(), feed.getUri()); break; case FEED_FILE: setFile(feed, mine); break; case FEED_MARKER: setMarker(); break; case FEED_AUDIO: setAudio(feed.getLength(), mine); break; } } public void onBind(@NonNull Feed feed, List<Object> payloads, @NonNull final String userId, final int avatarSize){ Bundle bundle = (Bundle) payloads.get(0); UserResource createdBy = bundle.getParcelable(NAMES.Server.CREATED_BY_ID); boolean mine = createdBy != null && createdBy.getUserId().equals(userId); for (String key : bundle.keySet()) { switch (key) { case NAMES.Server.CREATED_AT: setCreatedAt(feed.getCreatedAt()); break; case NAMES.Server.CREATED_BY_ID: if (createdBy != null) { setCreatedBy(createdBy, avatarSize); setColors(userId.equals(createdBy.getUserId())); } break; case NAMES.Server.TEXT: setText(feed.getShowingText()); break; case NAMES.Server.COUNT: setLikedCount(bundle.getInt(NAMES.Server.COUNT, 0)); break; case NAMES.MY_LIKE: setLiked(bundle.getBoolean(NAMES.MY_LIKE, false)); break; case NAMES.Server.LENGTH: setAudio(bundle.getLong(NAMES.Server.LENGTH, 0), createdBy != null && createdBy.getUserId().equals(userId)); break; case NAMES.Server.PLAN_ID: setMarker(); break; case NAMES.Server.CAPTION: setText(bundle.getString(NAMES.Server.CAPTION)); break; case NAMES.Server.URL: case NAMES.DB.PATH: String mimeType = bundle.getString(NAMES.Server.MIME_TYPE); if (mimeType != null && mimeType.contains(Constants.MimeType.IMAGE)) { setPicture(bundle.getString(NAMES.Server.URL), bundle.getString(NAMES.DB.PATH), null); } break; case SEEK_BAR_PROGRESS_BUNDLE: mAudioBar.setProgress(bundle.getInt(SEEK_BAR_PROGRESS_BUNDLE)); mAudioAction.setImageResource(bundle.getInt(ACTION_ICON_BUNDLE)); break; case RESET_AUDIO: resetAudio(bundle.getBoolean("mine")); break; } } } private void setCreatedBy(UserResource createdBy, final int avatarSize) { if (createdBy != null) { ImageLoader.newLoad(createdBy.getUrl(), Constants.Thumbnails.T72, mAvatar, avatarSize, avatarSize, R.drawable.unknown_user); mCreator.setText(createdBy.getName()); } } private void setCreatedAt(@NonNull Date createdAt) { mDate.setText(DateUtils.formatDate(createdAt, DateUtils.COMMENT_DATE)); } @SuppressWarnings("deprecation") private void setText(String text){ if (text != null) { mText.setVisibility(View.VISIBLE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { mText.setText(Html.fromHtml(text.replace("\n", "<br>"), Html.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE); }else { mText.setText(Html.fromHtml(text.replace("\n", "<br>")), TextView.BufferType.SPANNABLE); } }else { mText.setVisibility(View.GONE); } } private void setColors(boolean mine){ Context context = mCardView.getContext(); if (mine) { mCardView.setBackgroundColor(ContextCompat.getColor(context, MINE_BG_COLOR)); mText.setTextColor(ContextCompat.getColor(context, MINE_TEXT_COLOR)); mAudioLength.setTextColor(ContextCompat.getColor(context, MINE_TEXT_COLOR)); }else { mCardView.setBackgroundColor(ContextCompat.getColor(context, THEIR_BG_COLOR)); mText.setTextColor(ContextCompat.getColor(context, THEIR_TEXT_COLOR)); mAudioLength.setTextColor(ContextCompat.getColor(context, THEIR_TEXT_COLOR)); } } private void setLikedCount(final int count){ mLike.setText(String.format(Locale.getDefault(), "%d", count)); } private void setLiked(final boolean isLiked){ if (isLiked) { mLike.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_like, 0); }else { mLike.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_like_empty, 0); } } private void setPicture(final String url, final String path, final Uri uri){ mAudioLayout.setVisibility(View.GONE); if(url != null) { mPicture.setVisibility(View.VISIBLE); ImageLoader.newLoad(url, Constants.Thumbnails.T480, mPicture, mSize, mSize, R.color.white); }else if(path != null){ mPicture.setVisibility(View.VISIBLE); ImageLoader.newLoad(path, mPicture, mSize, mSize, R.color.white); }else if (uri != null) { mPicture.setVisibility(View.VISIBLE); ImageLoader.newLoad(uri, mPicture, mSize, mSize); }else { mPicture.setVisibility(View.GONE); } } private void setFile(@NonNull final Feed feed, final boolean mine){ mPicture.setVisibility(View.GONE); mText.setVisibility(View.VISIBLE); mAudioLayout.setVisibility(View.GONE); if (mine) { mText.setCompoundDrawablesRelativeWithIntrinsicBounds(MINE_FILE_ICON, 0, 0, 0); }else { mText.setCompoundDrawablesRelativeWithIntrinsicBounds(THEIR_FILE_ICON, 0, 0, 0); } mText.setText(feed.getName()); } private void setMarker(){ mPicture.setVisibility(View.GONE); mText.setVisibility(View.VISIBLE); mAudioLayout.setVisibility(View.GONE); mText.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_plan_gray, 0, 0, 0); mText.setText(R.string.feed_marker_placeholder); } private void setAudio(final long length, final boolean mine){ mPicture.setVisibility(View.GONE); mText.setVisibility(View.GONE); mAudioLayout.setVisibility(View.VISIBLE); if (mine) { mAudioAction.setImageResource(MINE_PLAY_ICON); }else { mAudioAction.setImageResource(THEIR_PLAY_ICON); } mAudioLength.setText(AndroidUtils._String.audioLength(length)); mAudioBar.setMax((int) (length / 1000) * 1000); //round mAudioBar.setProgress(0); } public void resetAudio(boolean mine){ if (mine) { mAudioAction.setImageResource(MINE_PLAY_ICON); mAudioBar.setProgress(0); }else { mAudioAction.setImageResource(THEIR_PLAY_ICON); mAudioBar.setProgress(0); } } public void setHolderSkeleton(int avatarImageResource, int bgColor){ mAvatar.setImageResource(avatarImageResource); mCreator.setText(""); mCreator.setBackgroundColor(bgColor); mDate.setText(""); mDate.setBackgroundColor(bgColor); mText.setText(""); mText.setBackgroundColor(bgColor); mPicture.setVisibility(View.GONE); mAudioLayout.setVisibility(View.GONE); mLike.setText(""); mLike.setBackgroundColor(bgColor); mLike.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } public void clearHolderSkeleton(){ mCreator.setBackgroundColor(0); mDate.setBackgroundColor(0); mText.setBackgroundColor(0); mLike.setBackgroundColor(0); } interface FeedHolderListener { void toggleLike(final int pos); void onLongClick(final int pos, final View v); void onClick(final int pos); int onAudioActionClicked(final int pos, final int progress); } } 时,输出字符串本身。

你正在制作这样的字符串:

console.log

当您"\"%ca\" + \"%cb\", \"color : red\", \"color : green\"" 结果时,您使用单个字符串参数调用console.log,该字符串参数将字符串记录为给定:

log

正确的调用将是三个参数:

 console.log("\"%ca\" + \"%cb\", \"color : red\", \"color : green\"");

您应该生成一个参数数组并使用 console.log("%ca%cb", "color : red", "color : green") 调用+,而不是输出包含一堆console.log个连接和逗号分隔参数的字符串:

apply

&#13;
&#13;
["%ca%cb", "color : red", "color : green"]
&#13;
&#13;
&#13;

请注意,StackOverflow的虚拟控制台不支持颜色。上述代码段的实际输出呈现如下:

enter image description here

答案 1 :(得分:1)

使用.reduce().map()简化您的功能实施。

var myString = "abcdefghijklmnopqrstuvwxyz";
var rainbow = ["red", "yellow", "pink", "green", "purple", "orange", "blue"];

function rainbowify(string) {
  var strArr = string.split("");
  var logs = [strArr.reduce((result, char) => result.concat("%c" + char + " "), "")];
    
  var logsWithColors = logs.concat(strArr.map((char, i) => {
    return "color: " + rainbow[i % rainbow.length] + ";"
  }));

  console.log.apply(console, logsWithColors);
}

rainbowify(myString);

在浏览器的控制台中生成以下内容:

enter image description here